#!/usr/bin/env python3
"""Simple Notion page updater for Mission slides."""

import os
import re
import json
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"
}

PAGES = {
    "ch1": "2f7330c2-8646-81fb-b2f4-fcf3db982b69",
    "ch2": "2f7330c2-8646-811c-a711-e9d16debbb8e", 
    "ch3": "2f7330c2-8646-81e4-a244-c4431864f484"
}

def clear_blocks(page_id):
    """Delete all blocks from page."""
    resp = requests.get(f"https://api.notion.com/v1/blocks/{page_id}/children?page_size=100", headers=HEADERS)
    if resp.status_code != 200:
        print(f"  Error getting blocks: {resp.status_code}")
        return
    for block in resp.json().get("results", []):
        requests.delete(f"https://api.notion.com/v1/blocks/{block['id']}", headers=HEADERS)

def md_to_blocks(md):
    """Convert markdown to Notion blocks (simplified)."""
    blocks = []
    for line in md.split("\n"):
        line = line.rstrip()
        if not line:
            continue
        if line == "---":
            blocks.append({"type": "divider", "divider": {}})
        elif line.startswith("# "):
            blocks.append({"type": "heading_1", "heading_1": {"rich_text": [{"type": "text", "text": {"content": line[2:]}}]}})
        elif line.startswith("## "):
            blocks.append({"type": "heading_2", "heading_2": {"rich_text": [{"type": "text", "text": {"content": line[3:]}}]}})
        elif line.startswith("### "):
            blocks.append({"type": "heading_3", "heading_3": {"rich_text": [{"type": "text", "text": {"content": line[4:]}}]}})
        elif line.startswith("> "):
            blocks.append({"type": "quote", "quote": {"rich_text": [{"type": "text", "text": {"content": line[2:]}}]}})
        elif line.startswith("- "):
            blocks.append({"type": "bulleted_list_item", "bulleted_list_item": {"rich_text": [{"type": "text", "text": {"content": line[2:]}}]}})
        elif re.match(r"^\d+\.\s", line):
            blocks.append({"type": "numbered_list_item", "numbered_list_item": {"rich_text": [{"type": "text", "text": {"content": re.sub(r'^\d+\.\s', '', line)}}]}})
        elif line.startswith("|"):
            # Tables as code blocks
            blocks.append({"type": "code", "code": {"rich_text": [{"type": "text", "text": {"content": line}}], "language": "plain text"}})
        else:
            blocks.append({"type": "paragraph", "paragraph": {"rich_text": [{"type": "text", "text": {"content": line}}]}})
    return blocks

def update_page(page_id, content):
    """Update page with content."""
    print(f"  Clearing old content...")
    clear_blocks(page_id)
    
    blocks = md_to_blocks(content)
    print(f"  Adding {len(blocks)} blocks...")
    
    # Add in batches of 100
    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: {resp.status_code} - {resp.text[:200]}")
            return False
    return True

def main():
    base = "/Users/assafdagan/clawd/projects/mission/research"
    files = {
        "ch1": f"{base}/slides-ch1-draft.md",
        "ch2": f"{base}/slides-ch2-draft.md",
        "ch3": f"{base}/slides-ch3-draft.md"
    }
    
    for ch, path in files.items():
        print(f"Updating {ch}...")
        with open(path) as f:
            content = f.read()
        if update_page(PAGES[ch], content):
            print(f"  ✓ Done")
        else:
            print(f"  ✗ Failed")

if __name__ == "__main__":
    main()
