#!/usr/bin/env python3
"""
Import the FULL Brand Content playbook directly to Notion page
"""

import requests
import json
import re

NOTION_KEY_PATH = '/home/clawd/secrets/notion/api_key'
NOTION_API = 'https://api.notion.com/v1'
PROJECT_PAGE_ID = '306330c2-8646-812a-bb8b-c6b39d28492a'

def get_headers():
    with open(NOTION_KEY_PATH) as f:
        api_key = f.read().strip()
    
    return {
        'Authorization': f'Bearer {api_key}',
        'Notion-Version': '2022-06-28',
        'Content-Type': 'application/json'
    }

def markdown_to_blocks(content):
    """Convert markdown content to Notion blocks"""
    lines = content.split('\n')
    blocks = []
    
    for line in lines:
        line = line.strip()
        if not line:
            continue
            
        # Headers
        if line.startswith('### '):
            blocks.append({
                "object": "block",
                "type": "heading_3",
                "heading_3": {
                    "rich_text": [{"text": {"content": line[4:]}}]
                }
            })
        elif line.startswith('## '):
            blocks.append({
                "object": "block", 
                "type": "heading_2",
                "heading_2": {
                    "rich_text": [{"text": {"content": line[3:]}}]
                }
            })
        elif line.startswith('# '):
            blocks.append({
                "object": "block",
                "type": "heading_1", 
                "heading_1": {
                    "rich_text": [{"text": {"content": line[2:]}}]
                }
            })
        # Bullet points
        elif line.startswith('- '):
            blocks.append({
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [{"text": {"content": line[2:]}}]
                }
            })
        # Numbered lists  
        elif re.match(r'^\d+\. ', line):
            content_text = re.sub(r'^\d+\. ', '', line)
            blocks.append({
                "object": "block",
                "type": "numbered_list_item",
                "numbered_list_item": {
                    "rich_text": [{"text": {"content": content_text}}]
                }
            })
        # Checkboxes
        elif line.startswith('- [ ] '):
            blocks.append({
                "object": "block",
                "type": "to_do",
                "to_do": {
                    "rich_text": [{"text": {"content": line[6:]}}],
                    "checked": False
                }
            })
        # Regular paragraphs
        else:
            # Skip empty lines and special formatting
            if line and not line.startswith('---') and not line.startswith('```'):
                blocks.append({
                    "object": "block",
                    "type": "paragraph",
                    "paragraph": {
                        "rich_text": [{"text": {"content": line}}]
                    }
                })
    
    return blocks

def import_content():
    print("🚀 Importing full Brand Content Architecture playbook...")
    
    # Read the formatted content
    try:
        with open('Brand_Content_Import_Formatted.md', 'r') as f:
            content = f.read()
    except FileNotFoundError:
        print("❌ Brand_Content_Import_Formatted.md not found")
        # Fallback to original playbook
        with open('Brand_Content_System_Architecture_Playbook.md', 'r') as f:
            content = f.read()
    
    # Convert to Notion blocks
    print("🔄 Converting markdown to Notion blocks...")
    blocks = markdown_to_blocks(content)
    
    print(f"📝 Created {len(blocks)} content blocks")
    
    # Import in chunks (Notion has 100 block limit per request)
    chunk_size = 90
    total_chunks = (len(blocks) + chunk_size - 1) // chunk_size
    
    for i in range(0, len(blocks), chunk_size):
        chunk_num = (i // chunk_size) + 1
        chunk = blocks[i:i + chunk_size]
        
        print(f"⬆️ Uploading chunk {chunk_num}/{total_chunks} ({len(chunk)} blocks)...")
        
        url = f"{NOTION_API}/blocks/{PROJECT_PAGE_ID}/children"
        payload = {"children": chunk}
        
        response = requests.patch(url, headers=get_headers(), json=payload)
        
        if response.status_code == 200:
            print(f"✅ Chunk {chunk_num} imported successfully")
        else:
            print(f"❌ Chunk {chunk_num} failed: {response.text}")
            break
    
    print("\\n🎉 Content import completed!")
    print(f"📄 View your page: https://notion.so/{PROJECT_PAGE_ID.replace('-', '')}")

if __name__ == "__main__":
    import_content()