#!/usr/bin/env python3
"""Rebuild Notion version history page with proper structure."""

import requests
import time

API_KEY = "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"
PAGE_ID = "300330c2-8646-8102-84ce-d2f75f15d5fa"
BASE_URL = "http://95.217.8.116:8800/mission/cards"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}

def delete_all_blocks():
    """Delete all children of the page."""
    url = f"https://api.notion.com/v1/blocks/{PAGE_ID}/children?page_size=100"
    while True:
        resp = requests.get(url, headers=HEADERS)
        data = resp.json()
        if "results" not in data or len(data["results"]) == 0:
            break
        for block in data["results"]:
            del_url = f"https://api.notion.com/v1/blocks/{block['id']}"
            requests.delete(del_url, headers=HEADERS)
            time.sleep(0.1)
        if not data.get("has_more"):
            break

def rich_text(text, bold=False, color="default"):
    """Create rich text object."""
    return {
        "type": "text",
        "text": {"content": text},
        "annotations": {
            "bold": bold,
            "italic": False,
            "strikethrough": False,
            "underline": False,
            "code": False,
            "color": color
        }
    }

def heading2(text):
    return {"object": "block", "type": "heading_2", "heading_2": {"rich_text": [rich_text(text)]}}

def heading3(text):
    return {"object": "block", "type": "heading_3", "heading_3": {"rich_text": [rich_text(text)]}}

def paragraph(texts):
    """texts is list of (text, bold, color) tuples"""
    return {
        "object": "block",
        "type": "paragraph",
        "paragraph": {"rich_text": [rich_text(t, b, c) for t, b, c in texts]}
    }

def callout(texts, emoji="📝", bg_color="gray_background"):
    return {
        "object": "block",
        "type": "callout",
        "callout": {
            "rich_text": [rich_text(t, b, c) for t, b, c in texts],
            "icon": {"type": "emoji", "emoji": emoji},
            "color": bg_color
        }
    }

def image(url):
    return {"object": "block", "type": "image", "image": {"type": "external", "external": {"url": url}}}

def divider():
    return {"object": "block", "type": "divider", "divider": {}}

def bullet(text):
    return {"object": "block", "type": "bulleted_list_item", "bulleted_list_item": {"rich_text": [rich_text(text)]}}

def append_blocks(blocks):
    """Append blocks in batches of 100."""
    url = f"https://api.notion.com/v1/blocks/{PAGE_ID}/children"
    for i in range(0, len(blocks), 100):
        batch = blocks[i:i+100]
        resp = requests.patch(url, headers=HEADERS, json={"children": batch})
        if resp.status_code != 200:
            print(f"Error: {resp.text}")
        time.sleep(0.3)

def build_page():
    blocks = []
    
    # Header
    blocks.append(callout([("Mission Family Illustrations - Version History", False, "default")], "📋", "blue_background"))
    blocks.append(paragraph([("Each version shows: prompt (", False, "default"), ("NEW elements in blue bold", True, "blue"), ("), images, and what differed from expected.", False, "default")]))
    blocks.append(divider())
    
    # Character Specs
    blocks.append(heading2("Character Specs (LOCKED)"))
    blocks.append(bullet("Dad: 50s, short gray hair, TRIM gray beard (NOT bushy), rosy cheeks"))
    blocks.append(bullet("Mom: 30s, brown ponytail, rosy cheeks"))
    blocks.append(bullet("Daughter: 5yo, blonde bob, rosy cheeks"))
    blocks.append(divider())
    
    # V1 - Target
    blocks.append(heading2("V1 - TARGET REFERENCE ✅"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([("Original reference image - prompt unknown. This is the approved style target.", False, "default")], "🎯", "green_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_lotion.png"))
    blocks.append(heading3("Key Style Elements"))
    blocks.append(bullet("BLACK line work (not sepia)"))
    blocks.append(bullet("FLAT solid colors - NO gradients, NO shading"))
    blocks.append(bullet("Clean digital vector-like coloring"))
    blocks.append(bullet("Only characters colored, backgrounds line art on cream"))
    blocks.append(divider())
    
    # V2 - Too Cartoonish
    blocks.append(heading2("V2 - Too Cartoonish ❌"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("Basic cartoon style. ", False, "default"),
        ("Added '5% more cartoonish' per request", True, "blue"),
        (". [Standard scene description]", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_v2.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("❌ Expected: Slightly more playful while keeping BD quality", False, "default")]))
    blocks.append(paragraph([("❌ Got: Lost European illustration quality, became generic cartoon", False, "default")]))
    blocks.append(paragraph([("💡 Learning: 'Cartoonish' triggers wrong style associations", False, "default")]))
    blocks.append(divider())
    
    # V3 - Too Serious
    blocks.append(heading2("V3 - Too Serious/Realistic ❌"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("European graphic novel style. ", False, "default"),
        ("'editorial realism', 'realistic proportions', 'watercolor-like'", True, "blue"),
        (". [Scene description]. Vertical 3:4.", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_v3.png"))
    blocks.append(image(f"{BASE_URL}/scene_hike_v3.png"))
    blocks.append(image(f"{BASE_URL}/scene_ski_v3.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("❌ Expected: European BD quality with warmth", False, "default")]))
    blocks.append(paragraph([("❌ Got: Too serious, lost playful warmth", False, "default")]))
    blocks.append(paragraph([("💡 Learning: 'Editorial realism' overcorrects away from cartoon warmth", False, "default")]))
    blocks.append(divider())
    
    # V4 - Good But Not Yet
    blocks.append(heading2("V4 - Good But Not Yet ⚠️"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("Simple ", False, "default"),
        ("warm cartoon", True, "blue"),
        (" illustration of [SCENE]. Clean ", False, "default"),
        ("black line art style with flat colors on characters, line work background", True, "blue"),
        (". [CHARACTER DESCRIPTIONS with rosy cheeks, friendly expressions]. Cream/beige background. Style: ", False, "default"),
        ("children's book illustration, warm and friendly. Simple faces with small eyes", True, "blue"),
        (". NOT realistic, NOT overly detailed. Vertical 3:4.", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_v4.png"))
    blocks.append(image(f"{BASE_URL}/scene_hike_v4.png"))
    blocks.append(image(f"{BASE_URL}/scene_ski_v4.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("✅ Got: Warmer feel, better line work", False, "default")]))
    blocks.append(paragraph([("⚠️ Still off: Color saturation not quite right", False, "default")]))
    blocks.append(paragraph([("💡 Learning: 'warm cartoon' + 'children's book' moves in right direction", False, "default")]))
    blocks.append(divider())
    
    # V5 - Too Muted
    blocks.append(heading2("V5 - Colors Too Muted ❌"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("Warm hand-drawn illustration style with ", False, "default"),
        ("bold varied line weights and cross-hatching details", True, "blue"),
        (". [Scene description]. ", False, "default"),
        ("Warm muted color palette, cozy nostalgic feel", True, "blue"),
        (". Cream background. Vertical 3:4.", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_v5.png"))
    blocks.append(image(f"{BASE_URL}/scene_hike_v5.png"))
    blocks.append(image(f"{BASE_URL}/scene_ski_v5.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("❌ Expected: Rich but not oversaturated colors", False, "default")]))
    blocks.append(paragraph([("❌ Got: Sepia/earthy tones - too desaturated", False, "default")]))
    blocks.append(paragraph([("💡 Learning: 'Warm muted' pushes too far toward brown/sepia", False, "default")]))
    blocks.append(divider())
    
    # V6 - Too Bright
    blocks.append(heading2("V6 - Colors Too Bright ❌"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("Clean warm cartoon illustration with bold varied line weights. [Scene with character descriptions]. ", False, "default"),
        ("CLEAN CREAM background, BRIGHT flat colors on characters - NOT muted, NOT sepia, NOT earthy", True, "blue"),
        (". Clean line work backgrounds. Children book illustration. Vertical 3:4.", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_v6.png"))
    blocks.append(image(f"{BASE_URL}/scene_hike_v6.png"))
    blocks.append(image(f"{BASE_URL}/scene_ski_v6.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("❌ Expected: Correct saturation between muted and bright", False, "default")]))
    blocks.append(paragraph([("❌ Got: Oversaturated, candy-bright colors", False, "default")]))
    blocks.append(paragraph([("💡 Learning: 'BRIGHT' overcorrects from V5's muted problem", False, "default")]))
    blocks.append(divider())
    
    # V7 - Better
    blocks.append(heading2("V7 - Better, Not Yet ⚠️"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("Clean warm cartoon illustration. [Scene]: Dad in off-white shirt and navy shorts, Mom in ", False, "default"),
        ("SOFT DUSTY CORAL", True, "blue"),
        (" swimsuit, Daughter in ", False, "default"),
        ("SOFT DUSTY PINK", True, "blue"),
        (". Background elements as ", False, "default"),
        ("LINE WORK ONLY on cream. ONLY characters have color", True, "blue"),
        (". ", False, "default"),
        ("Soft muted flat colors - NOT bright saturated, NOT sepia", True, "blue"),
        (". Children book illustration. Simple faces with small eyes. Vertical 3:4.", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_v7.png"))
    blocks.append(image(f"{BASE_URL}/scene_hike_v7.png"))
    blocks.append(image(f"{BASE_URL}/scene_ski_v7.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("✅ Got: Better color balance with 'soft dusty' palette", False, "default")]))
    blocks.append(paragraph([("✅ Got: Line work backgrounds working", False, "default")]))
    blocks.append(paragraph([("⚠️ Still off: Not quite matching V1 flatness", False, "default")]))
    blocks.append(paragraph([("💡 Learning: 'Soft dusty' is right direction for color naming", False, "default")]))
    blocks.append(divider())
    
    # V8 - Gradient Problem
    blocks.append(heading2("V8 - Still Has Gradients ❌"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("Heartwarming European children book illustration. ", False, "default"),
        ("WARM SEPIA-BROWN ink lines (NOT black)", True, "blue"),
        (", hand-drawn organic quality. [Scene]: Mom in TERRACOTTA swimsuit, Dad in cream shirt, Daughter in DUSTY PINK. ", False, "default"),
        ("Warm peachy skin tones with circular rosy cheek blush", True, "blue"),
        (". Background elements as ", False, "default"),
        ("UNCOLORED WARM BROWN LINE ART ONLY", True, "blue"),
        (" on cream. ONLY the three people have color. Simple faces, small dot eyes. Vertical 3:4.", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_beach_v8.png"))
    blocks.append(image(f"{BASE_URL}/scene_hike_v8.png"))
    blocks.append(image(f"{BASE_URL}/scene_ski_v8.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("❌ Expected: Warm hand-drawn feel with flat colors", False, "default")]))
    blocks.append(paragraph([("❌ Got: Watercolor-style gradients instead of flat fills", False, "default")]))
    blocks.append(paragraph([("💡 CRITICAL LEARNING: V1 uses BLACK lines + FLAT colors. Our analysis was WRONG.", False, "default")]))
    blocks.append(callout([
        ("V1 REANALYSIS: Lines are BLACK (not sepia). Colors are COMPLETELY FLAT - one solid color per area, NO gradients, NO shading. Clean digital vector-like coloring.", False, "default")
    ], "🚨", "red_background"))
    blocks.append(divider())
    
    # V9 - New Approach
    blocks.append(heading2("V9 - Flat Colors, 4 New Situations"))
    blocks.append(heading3("Prompt"))
    blocks.append(callout([
        ("Simple ", False, "default"),
        ("flat vector illustration, clean BLACK line art with FLAT solid color fills, NO gradients NO shading NO watercolor effects", True, "blue"),
        (". [SCENE]: Dad (50s, short gray hair, TRIM gray beard, rosy cheeks), Mom (30s, brown ponytail, rosy cheeks), Daughter (5yo, blonde bob, rosy cheeks). Clean cream background. Background elements as ", False, "default"),
        ("BLACK LINE ART ONLY with no color", True, "blue"),
        (". ONLY the three people have ", False, "default"),
        ("FLAT solid colors", True, "blue"),
        (". Simple faces, small dot eyes, circular pink cheek blush. Children book illustration. Vertical 3:4.", False, "default")
    ], "📝", "gray_background"))
    blocks.append(heading3("Images"))
    blocks.append(image(f"{BASE_URL}/scene_airport_v9.png"))
    blocks.append(image(f"{BASE_URL}/scene_grocery_v9.png"))
    blocks.append(image(f"{BASE_URL}/scene_kite_v9.png"))
    blocks.append(image(f"{BASE_URL}/scene_restaurant_v9.png"))
    blocks.append(heading3("Prompt vs Result"))
    blocks.append(paragraph([("Status: Awaiting review", False, "default")]))
    blocks.append(divider())
    
    # Color Spectrum Summary
    blocks.append(heading2("📊 Color Spectrum Summary"))
    blocks.append(callout([("TOO MUTED (V5: sepia) ← TARGET (V1: flat, soft dusty) → TOO BRIGHT (V6: saturated)", False, "default")], "🎨", "yellow_background"))
    blocks.append(divider())
    
    # 30% Color Rule
    blocks.append(heading2("30% Color Rule"))
    blocks.append(paragraph([("ONLY characters get color. Backgrounds = BLACK LINE WORK on cream. No colored backgrounds.", False, "default")]))
    
    return blocks

if __name__ == "__main__":
    print("Deleting existing blocks...")
    delete_all_blocks()
    print("Building new page structure...")
    blocks = build_page()
    print(f"Appending {len(blocks)} blocks...")
    append_blocks(blocks)
    print("Done!")
