#!/usr/bin/env python3
"""
Final import script to add ALL Brand content to Notion page.
Using working curl format as reference.
"""

import json
import requests
import os
import time
import re

# 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():
    with open(NOTION_KEY_PATH) as f:
        return f.read().strip()

def notion_headers():
    return {
        "Authorization": f"Bearer {get_notion_key()}",
        "Notion-Version": NOTION_VERSION,
        "Content-Type": "application/json"
    }

def create_text_block(content, block_type="paragraph"):
    """Create a properly formatted text block."""
    return {
        "object": "block",
        "type": block_type,
        block_type: {
            "rich_text": [
                {
                    "type": "text",
                    "text": {"content": content}
                }
            ]
        }
    }

def create_heading_block(content, level=1):
    """Create a heading block."""
    heading_type = f"heading_{level}"
    return {
        "object": "block",
        "type": heading_type,
        heading_type: {
            "rich_text": [
                {
                    "type": "text",
                    "text": {"content": content}
                }
            ]
        }
    }

def create_list_item(content, item_type="bulleted_list_item"):
    """Create a list item block."""
    return {
        "object": "block",
        "type": item_type,
        item_type: {
            "rich_text": [
                {
                    "type": "text",
                    "text": {"content": content}
                }
            ]
        }
    }

def create_divider():
    """Create a divider block."""
    return {
        "object": "block",
        "type": "divider",
        "divider": {}
    }

def parse_markdown_section(content):
    """Parse a markdown section into Notion blocks."""
    blocks = []
    lines = content.split('\n')
    
    for line in lines:
        line = line.strip()
        
        if not line:
            continue
            
        # Handle headings
        if line.startswith('#'):
            heading_level = len(re.match(r'^#+', line).group())
            text = line.lstrip('# ').strip()
            heading_level = min(heading_level, 3)  # Notion supports up to heading_3
            blocks.append(create_heading_block(text, heading_level))
            
        # Handle bullet points
        elif line.startswith(('-', '*', '•')):
            text = line.lstrip('-* •').strip()
            blocks.append(create_list_item(text, "bulleted_list_item"))
            
        # Handle numbered lists
        elif re.match(r'^\d+\.', line):
            text = re.sub(r'^\d+\.\s*', '', line)
            blocks.append(create_list_item(text, "numbered_list_item"))
            
        # Handle dividers
        elif line in ['---', '***', '___']:
            blocks.append(create_divider())
            
        # Regular paragraphs
        else:
            # Skip very long lines or problematic content
            if len(line) > 2000:
                # Split long lines into chunks
                words = line.split()
                chunk = []
                for word in words:
                    if len(' '.join(chunk + [word])) > 1500:
                        if chunk:
                            blocks.append(create_text_block(' '.join(chunk)))
                        chunk = [word]
                    else:
                        chunk.append(word)
                if chunk:
                    blocks.append(create_text_block(' '.join(chunk)))
            else:
                blocks.append(create_text_block(line))
    
    return blocks

def add_blocks_batch(blocks, batch_size=25):
    """Add blocks to the page in small batches."""
    url = f"{NOTION_API}/blocks/{TARGET_PAGE_ID}/children"
    
    total_blocks = len(blocks)
    successful_blocks = 0
    
    print(f"Adding {total_blocks} blocks in batches of {batch_size}...")
    
    for i in range(0, len(blocks), batch_size):
        batch = blocks[i:i + batch_size]
        
        payload = {"children": batch}
        
        try:
            response = requests.patch(url, headers=notion_headers(), json=payload, timeout=30)
            
            if response.status_code == 200:
                successful_blocks += len(batch)
                print(f"✅ Batch {i//batch_size + 1}: Added {len(batch)} blocks ({successful_blocks}/{total_blocks} total)")
            else:
                print(f"❌ Batch {i//batch_size + 1} failed: {response.status_code}")
                print(f"   Response: {response.text[:200]}...")
                
        except Exception as e:
            print(f"❌ Exception in batch {i//batch_size + 1}: {e}")
            
        # Small delay between batches to avoid rate limiting
        time.sleep(0.5)
    
    print(f"\nImport completed: {successful_blocks}/{total_blocks} blocks added successfully")
    return successful_blocks

def main():
    print("🚀 Final Brand Content Import to Notion")
    print("=" * 50)
    
    try:
        # Read the markdown content
        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")
        
        # Parse content to blocks
        print("2️⃣ Converting to Notion blocks...")
        blocks = parse_markdown_section(content)
        print(f"   ✅ Created {len(blocks)} blocks")
        
        # Add blocks to page
        print("3️⃣ Adding blocks to Notion page...")
        successful_count = add_blocks_batch(blocks)
        
        if successful_count > 0:
            print(f"\n🎉 SUCCESS! Added {successful_count} blocks to the page.")
            print(f"📄 View the page: https://notion.so/{TARGET_PAGE_ID}")
        else:
            print("\n❌ No blocks were successfully added.")
            
    except FileNotFoundError:
        print("❌ Brand_Content_Import_Formatted.md not found")
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    main()