#!/usr/bin/env python3
"""
Import the complete Brand_Content_Import_Formatted.md content into the specific Notion page.
Converts markdown to Notion blocks and populates the page with all 22k words of content.
"""

import json
import requests
import os
import re
from typing import List, Dict, Any

# Configuration
NOTION_KEY_PATH = "/home/clawd/secrets/notion/api_key"
NOTION_API = "https://api.notion.com/v1"
NOTION_VERSION = "2022-06-28"
TARGET_PAGE_ID = "306330c2-8646-812a-bb8b-c6b39d28492a"

def get_notion_key():
    """Get the Notion API key."""
    with open(NOTION_KEY_PATH) as f:
        return f.read().strip()

def notion_headers():
    """Get headers for Notion API requests."""
    return {
        "Authorization": f"Bearer {get_notion_key()}",
        "Notion-Version": NOTION_VERSION,
        "Content-Type": "application/json"
    }

def parse_markdown_to_blocks(content: str) -> List[Dict[str, Any]]:
    """Parse markdown content into Notion blocks."""
    blocks = []
    lines = content.split('\n')
    i = 0
    
    while i < len(lines):
        line = lines[i].strip()
        
        # Skip empty lines
        if not line:
            i += 1
            continue
        
        # Handle headings
        if line.startswith('#'):
            heading_level = len(re.match(r'^#+', line).group())
            text = line.lstrip('# ').strip()
            
            if heading_level == 1:
                block_type = "heading_1"
            elif heading_level == 2:
                block_type = "heading_2"
            else:
                block_type = "heading_3"
                
            blocks.append({
                "object": "block",
                "type": block_type,
                block_type: {
                    "rich_text": [{"text": {"content": text}}]
                }
            })
            
        # Handle bullet points
        elif line.startswith(('-', '*', '•')):
            text = line.lstrip('-* •').strip()
            blocks.append({
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [{"text": {"content": text}}]
                }
            })
            
        # Handle numbered lists
        elif re.match(r'^\d+\.', line):
            text = re.sub(r'^\d+\.\s*', '', line)
            blocks.append({
                "object": "block",
                "type": "numbered_list_item",
                "numbered_list_item": {
                    "rich_text": [{"text": {"content": text}}]
                }
            })
            
        # Handle checkboxes
        elif '- [ ]' in line or '- [x]' in line:
            checked = '[x]' in line
            text = re.sub(r'- \[[x ]\] ', '', line)
            blocks.append({
                "object": "block",
                "type": "to_do",
                "to_do": {
                    "rich_text": [{"text": {"content": text}}],
                    "checked": checked
                }
            })
            
        # Handle code blocks
        elif line.startswith('```'):
            code_content = []
            i += 1
            while i < len(lines) and not lines[i].strip().startswith('```'):
                code_content.append(lines[i])
                i += 1
                
            blocks.append({
                "object": "block",
                "type": "code",
                "code": {
                    "rich_text": [{"text": {"content": '\n'.join(code_content)}}],
                    "language": "plain text"
                }
            })
            
        # Handle dividers
        elif line in ['---', '***', '___']:
            blocks.append({
                "object": "block",
                "type": "divider",
                "divider": {}
            })
            
        # Handle quotes
        elif line.startswith('>'):
            text = line.lstrip('> ').strip()
            blocks.append({
                "object": "block",
                "type": "quote",
                "quote": {
                    "rich_text": [{"text": {"content": text}}]
                }
            })
            
        # Handle tables - simplified (convert to bulleted list for now)
        elif '|' in line and line.startswith('|'):
            cells = [cell.strip() for cell in line.split('|')[1:-1]]
            text = ' • '.join(cells)
            blocks.append({
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [{"text": {"content": text}}]
                }
            })
            
        # Regular paragraphs
        else:
            # Handle bold and italic text
            rich_text = parse_rich_text(line)
            blocks.append({
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": rich_text
                }
            })
            
        i += 1
    
    return blocks

def parse_rich_text(text: str) -> List[Dict[str, Any]]:
    """Parse text with markdown formatting into Notion rich text."""
    rich_text = []
    
    # Simple parsing for bold (**text**) and italic (*text*)
    parts = re.split(r'(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`)', text)
    
    for part in parts:
        if part.startswith('**') and part.endswith('**'):
            # Bold text
            content = part[2:-2]
            rich_text.append({
                "text": {"content": content},
                "annotations": {"bold": True}
            })
        elif part.startswith('*') and part.endswith('*') and not part.startswith('**'):
            # Italic text
            content = part[1:-1]
            rich_text.append({
                "text": {"content": content},
                "annotations": {"italic": True}
            })
        elif part.startswith('`') and part.endswith('`'):
            # Code text
            content = part[1:-1]
            rich_text.append({
                "text": {"content": content},
                "annotations": {"code": True}
            })
        elif part:
            # Regular text
            rich_text.append({
                "text": {"content": part}
            })
    
    return rich_text if rich_text else [{"text": {"content": text}}]

def add_blocks_to_page(page_id: str, blocks: List[Dict[str, Any]]) -> None:
    """Add blocks to a Notion page in batches."""
    url = f"{NOTION_API}/blocks/{page_id}/children"
    
    # Notion API has a limit of 100 blocks per request, but let's use smaller batches for reliability
    batch_size = 50
    successful_batches = 0
    
    for i in range(0, len(blocks), batch_size):
        batch = blocks[i:i + batch_size]
        payload = {"children": batch}
        
        print(f"Adding blocks {i+1} to {min(i+batch_size, len(blocks))} of {len(blocks)}")
        
        try:
            response = requests.patch(url, headers=notion_headers(), json=payload)
            
            if response.status_code != 200:
                print(f"Error adding batch {i//batch_size + 1}: {response.status_code}")
                print(f"Response: {response.text}")
                
                # Try to add blocks one by one if batch fails
                print(f"Trying to add blocks individually...")
                for j, block in enumerate(batch):
                    individual_payload = {"children": [block]}
                    individual_response = requests.patch(url, headers=notion_headers(), json=individual_payload)
                    if individual_response.status_code == 200:
                        print(f"  ✅ Block {i+j+1} added individually")
                    else:
                        print(f"  ❌ Failed to add block {i+j+1}: {individual_response.status_code}")
                        # Skip problematic blocks and continue
                        continue
            else:
                successful_batches += 1
                print(f"✅ Successfully added batch {i//batch_size + 1}")
                
        except Exception as e:
            print(f"Exception adding batch {i//batch_size + 1}: {e}")
            continue
    
    print(f"Import completed. {successful_batches} batches succeeded out of {(len(blocks) + batch_size - 1) // batch_size} total.")

def clear_page_content(page_id: str) -> None:
    """Clear existing content from the page."""
    url = f"{NOTION_API}/blocks/{page_id}/children"
    
    # Get existing blocks
    response = requests.get(url, headers=notion_headers())
    if response.status_code != 200:
        print(f"Error fetching existing blocks: {response.status_code}")
        return
    
    existing_blocks = response.json().get("results", [])
    
    if existing_blocks:
        print(f"Found {len(existing_blocks)} existing blocks. Clearing page...")
        
        # Delete each block
        for block in existing_blocks:
            delete_url = f"{NOTION_API}/blocks/{block['id']}"
            delete_response = requests.delete(delete_url, headers=notion_headers())
            if delete_response.status_code not in [200, 404]:
                print(f"Warning: Could not delete block {block['id']}: {delete_response.status_code}")
        
        print("✅ Page cleared")
    else:
        print("Page is already empty")

def verify_page_exists(page_id: str) -> bool:
    """Verify that the target page exists and is accessible."""
    url = f"{NOTION_API}/pages/{page_id}"
    response = requests.get(url, headers=notion_headers())
    
    if response.status_code == 200:
        page_data = response.json()
        print(f"   ✅ Page found: {page_data.get('properties', {}).get('title', {}).get('title', [{}])[0].get('plain_text', 'Untitled')}")
        return True
    else:
        print(f"   ❌ Page not accessible: {response.status_code}")
        print(f"   Response: {response.text}")
        return False

def main():
    print("🚀 Importing Brand Content Architecture into Notion")
    print("=" * 60)
    
    try:
        # Step 0: Verify page exists
        print("0️⃣ Verifying target page exists...")
        if not verify_page_exists(TARGET_PAGE_ID):
            print("❌ Cannot access target page. Exiting.")
            return
        
        # Step 1: Read the markdown file
        print("1️⃣ Reading Brand_Content_Import_Formatted.md...")
        with open("Brand_Content_Import_Formatted.md", "r", encoding="utf-8") as f:
            content = f.read()
        print(f"   ✅ Read {len(content)} characters")
        
        # Step 2: Clear existing page content
        print("2️⃣ Clearing existing page content...")
        clear_page_content(TARGET_PAGE_ID)
        
        # Step 3: Parse markdown to Notion blocks
        print("3️⃣ Converting markdown to Notion blocks...")
        blocks = parse_markdown_to_blocks(content)
        print(f"   ✅ Created {len(blocks)} blocks")
        
        # Step 4: Add all blocks to the page
        print("4️⃣ Adding content to Notion page...")
        add_blocks_to_page(TARGET_PAGE_ID, blocks)
        
        print(f"\n🎉 SUCCESS! Imported complete content to page {TARGET_PAGE_ID}")
        print(f"📊 Total blocks added: {len(blocks)}")
        print(f"📄 View the page: https://notion.so/{TARGET_PAGE_ID}")
        
    except FileNotFoundError:
        print("❌ Error: Brand_Content_Import_Formatted.md file not found")
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()