#!/usr/bin/env python3
"""Update Mission slide pages in Notion with content from markdown files."""

import os
import re
import requests

API_KEY = open(os.path.expanduser("~/.config/notion/api_key")).read().strip()
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28"
}

# Page IDs from HEARTBEAT.md and Notion
PAGES = {
    "ch1": "2f7330c2864681d9a083c24e0b7da5f0",  # Will search for this
    "ch2": "2f7330c2864681f192efec89db83c65d",
    "ch3": "2f7330c286468165882fce99711c5874"
}

def search_page(title_contains):
    """Search for a page by title."""
    resp = requests.post(
        "https://api.notion.com/v1/search",
        headers=HEADERS,
        json={"query": title_contains, "filter": {"property": "object", "value": "page"}}
    )
    results = resp.json().get("results", [])
    for r in results:
        title = ""
        if "title" in r.get("properties", {}):
            title_prop = r["properties"]["title"]
            if "title" in title_prop and title_prop["title"]:
                title = title_prop["title"][0].get("plain_text", "")
        elif "child_page" in r:
            title = r["child_page"].get("title", "")
        if title_contains.lower() in title.lower():
            return r["id"]
    return None

def md_to_blocks(md_content):
    """Convert markdown to Notion blocks."""
    blocks = []
    lines = md_content.split("\n")
    i = 0
    
    while i < len(lines):
        line = lines[i]
        
        # Skip empty lines
        if not line.strip():
            i += 1
            continue
        
        # H1
        if line.startswith("# "):
            blocks.append({
                "object": "block",
                "type": "heading_1",
                "heading_1": {"rich_text": [{"type": "text", "text": {"content": line[2:].strip()}}]}
            })
        # H2
        elif line.startswith("## "):
            blocks.append({
                "object": "block",
                "type": "heading_2", 
                "heading_2": {"rich_text": [{"type": "text", "text": {"content": line[3:].strip()}}]}
            })
        # H3
        elif line.startswith("### "):
            blocks.append({
                "object": "block",
                "type": "heading_3",
                "heading_3": {"rich_text": [{"type": "text", "text": {"content": line[4:].strip()}}]}
            })
        # Horizontal rule
        elif line.strip() == "---":
            blocks.append({"object": "block", "type": "divider", "divider": {}})
        # Blockquote
        elif line.startswith("> "):
            blocks.append({
                "object": "block",
                "type": "quote",
                "quote": {"rich_text": [{"type": "text", "text": {"content": line[2:].strip()}}]}
            })
        # Table (simplified - just as text for now)
        elif line.startswith("|"):
            # Collect table lines
            table_lines = [line]
            i += 1
            while i < len(lines) and lines[i].startswith("|"):
                table_lines.append(lines[i])
                i += 1
            # Add as code block to preserve formatting
            blocks.append({
                "object": "block",
                "type": "code",
                "code": {
                    "rich_text": [{"type": "text", "text": {"content": "\n".join(table_lines)}}],
                    "language": "plain text"
                }
            })
            continue
        # Bullet point
        elif line.startswith("- "):
            blocks.append({
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {"rich_text": [{"type": "text", "text": {"content": line[2:].strip()}}]}
            })
        # Numbered list
        elif re.match(r"^\d+\.\s", line):
            content = re.sub(r"^\d+\.\s", "", line)
            blocks.append({
                "object": "block",
                "type": "numbered_list_item",
                "numbered_list_item": {"rich_text": [{"type": "text", "text": {"content": content.strip()}}]}
            })
        # Regular paragraph
        else:
            # Handle bold and italic in text
            text = line.strip()
            if text:
                blocks.append({
                    "object": "block",
                    "type": "paragraph",
                    "paragraph": {"rich_text": [{"type": "text", "text": {"content": text}}]}
                })
        
        i += 1
    
    return blocks

def clear_page_content(page_id):
    """Get and delete all blocks from a page."""
    # Get existing blocks
    resp = requests.get(
        f"https://api.notion.com/v1/blocks/{page_id}/children",
        headers=HEADERS
    )
    blocks = resp.json().get("results", [])
    
    # Delete each block
    for block in blocks:
        requests.delete(f"https://api.notion.com/v1/blocks/{block['id']}", headers=HEADERS)

def update_page(page_id, md_content):
    """Update a Notion page with markdown content."""
    # Clear existing content
    clear_page_content(page_id)
    
    # Convert markdown to blocks
    blocks = md_to_blocks(md_content)
    
    # Add blocks in batches of 100 (API limit)
    for i in range(0, len(blocks), 100):
        batch = blocks[i:i+100]
        resp = requests.patch(
            f"https://api.notion.com/v1/blocks/{page_id}/children",
            headers=HEADERS,
            json={"children": batch}
        )
        if resp.status_code != 200:
            print(f"Error adding blocks: {resp.text}")
            return False
    
    return True

def main():
    base_path = "/Users/assafdagan/clawd/projects/mission/research"
    
    # Find Ch1 slides page
    ch1_id = search_page("Ch 1: Slides")
    if ch1_id:
        PAGES["ch1"] = ch1_id.replace("-", "")
        print(f"Found Ch1 page: {ch1_id}")
    else:
        print("Warning: Could not find Ch1 slides page")
        PAGES["ch1"] = None
    
    files = {
        "ch1": f"{base_path}/slides-ch1-draft.md",
        "ch2": f"{base_path}/slides-ch2-draft.md", 
        "ch3": f"{base_path}/slides-ch3-draft.md"
    }
    
    for ch, filepath in files.items():
        page_id = PAGES.get(ch)
        if not page_id:
            print(f"Skipping {ch} - no page ID")
            continue
            
        print(f"Updating {ch}...")
        with open(filepath) as f:
            content = f.read()
        
        if update_page(page_id, content):
            print(f"  ✓ {ch} updated")
        else:
            print(f"  ✗ {ch} failed")

if __name__ == "__main__":
    main()
