#!/usr/bin/env python3
"""Convert Notion blocks JSON to WordPress-ready HTML."""
import json, subprocess, sys, os

API_KEY = "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"
NOTION_VERSION = "2025-09-03"

def fetch_children(block_id):
    """Fetch children blocks for a given block ID."""
    import urllib.request
    url = f"https://api.notion.com/v1/blocks/{block_id}/children?page_size=100"
    req = urllib.request.Request(url, headers={
        "Authorization": f"Bearer {API_KEY}",
        "Notion-Version": NOTION_VERSION
    })
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read())["results"]

def rich_text_to_html(rich_texts):
    """Convert Notion rich_text array to HTML string."""
    html = ""
    for rt in rich_texts:
        text = rt.get("plain_text", "")
        # Escape HTML entities
        text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        ann = rt.get("annotations", {})
        href = rt.get("href")
        if ann.get("code"):
            text = f"<code>{text}</code>"
        if ann.get("bold"):
            text = f"<strong>{text}</strong>"
        if ann.get("italic"):
            text = f"<em>{text}</em>"
        if ann.get("strikethrough"):
            text = f"<s>{text}</s>"
        if ann.get("underline"):
            text = f"<u>{text}</u>"
        if href:
            text = f'<a href="{href}">{text}</a>'
        html += text
    return html

def blocks_to_html(blocks):
    """Convert a list of Notion blocks to HTML."""
    html_parts = []
    i = 0
    while i < len(blocks):
        block = blocks[i]
        btype = block["type"]
        
        if btype == "heading_1":
            content = rich_text_to_html(block["heading_1"]["rich_text"])
            html_parts.append(f"<h1>{content}</h1>")
        
        elif btype == "heading_2":
            content = rich_text_to_html(block["heading_2"]["rich_text"])
            html_parts.append(f"<h2>{content}</h2>")
        
        elif btype == "heading_3":
            content = rich_text_to_html(block["heading_3"]["rich_text"])
            html_parts.append(f"<h3>{content}</h3>")
        
        elif btype == "paragraph":
            content = rich_text_to_html(block["paragraph"]["rich_text"])
            if content:
                html_parts.append(f"<p>{content}</p>")
        
        elif btype == "bulleted_list_item":
            items = []
            while i < len(blocks) and blocks[i]["type"] == "bulleted_list_item":
                content = rich_text_to_html(blocks[i]["bulleted_list_item"]["rich_text"])
                items.append(f"<li>{content}</li>")
                i += 1
            html_parts.append("<ul>\n" + "\n".join(items) + "\n</ul>")
            continue  # skip i increment at end
        
        elif btype == "numbered_list_item":
            items = []
            while i < len(blocks) and blocks[i]["type"] == "numbered_list_item":
                content = rich_text_to_html(blocks[i]["numbered_list_item"]["rich_text"])
                items.append(f"<li>{content}</li>")
                i += 1
            html_parts.append("<ol>\n" + "\n".join(items) + "\n</ol>")
            continue
        
        elif btype == "quote":
            content = rich_text_to_html(block["quote"]["rich_text"])
            html_parts.append(f"<blockquote><p>{content}</p></blockquote>")
        
        elif btype == "code":
            content = rich_text_to_html(block["code"]["rich_text"])
            lang = block["code"].get("language", "")
            html_parts.append(f"<pre><code>{content}</code></pre>")
        
        elif btype == "divider":
            html_parts.append("<hr>")
        
        elif btype == "table":
            if block.get("has_children"):
                rows = fetch_children(block["id"])
                table_html = "<table>\n"
                has_header = block["table"].get("has_column_header", False)
                for ri, row in enumerate(rows):
                    if row["type"] == "table_row":
                        cells = row["table_row"]["cells"]
                        tag = "th" if (ri == 0 and has_header) else "td"
                        row_html = "<tr>"
                        for cell in cells:
                            cell_content = rich_text_to_html(cell)
                            row_html += f"<{tag}>{cell_content}</{tag}>"
                        row_html += "</tr>\n"
                        table_html += row_html
                table_html += "</table>"
                html_parts.append(table_html)
        
        i += 1
    
    return "\n\n".join(html_parts)

# Process all three posts
posts = [
    {
        "page_id": "2f8d6b58-6a7e-81be-9a83-e2f5ba76e191",
        "title": "CalWizz vs Reclaim.ai",
        "file": "post1.json"
    },
    {
        "page_id": "2f8d6b58-6a7e-81ec-8c1e-c528a31d6c28",
        "title": "True Cost of a 1-Hour Meeting",
        "file": "post2.json"
    },
    {
        "page_id": "2f8d6b58-6a7e-8181-826f-c26bc4115996",
        "title": "The 3-2-1 Calendar Audit",
        "file": "post3.json"
    }
]

# Fetch blocks for each post
for post in posts:
    print(f"Fetching blocks for: {post['title']}")
    blocks = fetch_children(post["page_id"])
    print(f"  Got {len(blocks)} blocks")
    
    print(f"Converting to HTML...")
    html = blocks_to_html(blocks)
    
    # Write HTML file
    html_file = f"/root/clawd/drafts/{post['file'].replace('.json', '.html')}"
    with open(html_file, 'w') as f:
        f.write(html)
    post["html_file"] = html_file
    print(f"  Written to {html_file}")
    print(f"  HTML length: {len(html)} chars")

print("\nAll posts converted successfully!")
for p in posts:
    print(f"  {p['title']}: {p['html_file']}")
