#!/usr/bin/env python3
"""
Add Studio Dado case study to Notion Inspiration Library.
Creates a new entry with proper tags and structure.
"""

import json
import requests
import os
from datetime import datetime
from typing import List, Dict, Any

# Configuration
NOTION_KEY_PATH = "/home/clawd/secrets/notion/api_key"
NOTION_API = "https://api.notion.com/v1"
NOTION_VERSION = "2022-06-28"
INSPIRATION_LIBRARY_ID = "2ff330c2-8646-81f0-bbd9-ec474393d7a5"

def get_notion_key():
    """Get the Notion API key."""
    with open(NOTION_KEY_PATH) as f:
        return f.read().strip()

def notion_headers():
    """Get headers for Notion API requests."""
    return {
        "Authorization": f"Bearer {get_notion_key()}",
        "Notion-Version": NOTION_VERSION,
        "Content-Type": "application/json"
    }

def create_studio_dado_entry() -> List[Dict[str, Any]]:
    """Create the content blocks for Studio Dado inspiration entry."""
    blocks = [
        {
            "object": "block",
            "type": "heading_2",
            "heading_2": {
                "rich_text": [{"text": {"content": "Studio Dado — Identity & Branding"}}]
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Source: "}},
                    {"text": {"content": "We Are Motto", "annotations": {"bold": True}}},
                    {"text": {"content": " (design studio portfolio)"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "URL: "}},
                    {"text": {
                        "content": "https://wearemotto.com/portfolio/studio-dado",
                        "link": {"url": "https://wearemotto.com/portfolio/studio-dado"}
                    }}
                ]
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Submitted by: "}},
                    {"text": {"content": "Assaf", "annotations": {"italic": True}}},
                    {"text": {"content": " in #visual-input"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Added: "}},
                    {"text": {"content": datetime.now().strftime("%Y-%m-%d %H:%M UTC")}}
                ]
            }
        },
        {
            "object": "block",
            "type": "divider",
            "divider": {}
        },
        {
            "object": "block",
            "type": "heading_3",
            "heading_3": {
                "rich_text": [{"text": {"content": "Project Overview"}}]
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Case study showcasing We Are Motto's branding and identity work for Studio Dado. This reference demonstrates contemporary approaches to studio identity systems and brand architecture."}}
                ]
            }
        },
        {
            "object": "block",
            "type": "heading_3",
            "heading_3": {
                "rich_text": [{"text": {"content": "Tags & Categories"}}]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "branding", "annotations": {"code": True}}}
                ]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "identity", "annotations": {"code": True}}}
                ]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "studio", "annotations": {"code": True}}}
                ]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "portfolio", "annotations": {"code": True}}}
                ]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "case-study", "annotations": {"code": True}}}
                ]
            }
        },
        {
            "object": "block",
            "type": "divider",
            "divider": {}
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Note: ", "annotations": {"bold": True}}},
                    {"text": {"content": "Visual content capture limited due to site protection. Recommend manual review for detailed visual analysis and screenshot curation.", "annotations": {"italic": True}}}
                ]
            }
        }
    ]
    
    return blocks

def add_blocks_to_page(page_id: str, blocks: List[Dict[str, Any]]) -> None:
    """Add blocks to a Notion page."""
    url = f"{NOTION_API}/blocks/{page_id}/children"
    payload = {"children": blocks}
    
    print(f"Adding {len(blocks)} blocks to inspiration library...")
    
    try:
        response = requests.patch(url, headers=notion_headers(), json=payload)
        
        if response.status_code == 200:
            print("✅ Successfully added Studio Dado entry to Inspiration Library")
        else:
            print(f"❌ Error: {response.status_code}")
            print(f"Response: {response.text}")
            
            # If batch fails, try individual blocks
            print("Attempting to add blocks individually...")
            for i, block in enumerate(blocks):
                individual_payload = {"children": [block]}
                individual_response = requests.patch(url, headers=notion_headers(), json=individual_payload)
                if individual_response.status_code == 200:
                    print(f"  ✅ Block {i+1} added")
                else:
                    print(f"  ❌ Block {i+1} failed: {individual_response.status_code}")
                    
    except Exception as e:
        print(f"Exception: {e}")

def verify_page_exists(page_id: str) -> bool:
    """Verify that the target page exists and is accessible."""
    url = f"{NOTION_API}/pages/{page_id}"
    print(f"   🔍 Checking URL: {url}")
    print(f"   🔑 API Key: {get_notion_key()[:20]}...")
    
    response = requests.get(url, headers=notion_headers())
    
    print(f"   📡 Response status: {response.status_code}")
    if response.status_code != 200:
        print(f"   📄 Response text: {response.text}")
    
    if response.status_code == 200:
        page_data = response.json()
        page_title = "Unknown"
        if 'properties' in page_data:
            title_prop = page_data['properties'].get('title', {}).get('title', [])
            if title_prop:
                page_title = title_prop[0].get('plain_text', 'Unknown')
        print(f"   ✅ Inspiration Library found: {page_title}")
        return True
    else:
        print(f"   ❌ Page not accessible: {response.status_code}")
        
        # Try alternative page ID formats
        print("   🔄 Trying alternative page ID formats...")
        
        # Try with dashes removed
        clean_id = page_id.replace('-', '')
        alt_url = f"{NOTION_API}/pages/{clean_id}"
        print(f"   🔍 Trying clean ID: {alt_url}")
        alt_response = requests.get(alt_url, headers=notion_headers())
        print(f"   📡 Clean ID response: {alt_response.status_code}")
        
        # Try as database instead of page
        db_url = f"{NOTION_API}/databases/{page_id}"
        print(f"   🔍 Trying as database: {db_url}")
        db_response = requests.get(db_url, headers=notion_headers())
        print(f"   📡 Database response: {db_response.status_code}")
        
        return False

def main():
    print("📌 Adding Studio Dado to Notion Inspiration Library")
    print("=" * 50)
    
    try:
        # Step 1: Verify page exists
        print("1️⃣ Verifying Inspiration Library access...")
        if not verify_page_exists(INSPIRATION_LIBRARY_ID):
            print("❌ Cannot access Inspiration Library. Exiting.")
            return
        
        # Step 2: Create content blocks
        print("2️⃣ Creating Studio Dado entry content...")
        blocks = create_studio_dado_entry()
        print(f"   ✅ Created {len(blocks)} content blocks")
        
        # Step 3: Add to Notion
        print("3️⃣ Adding to Notion Inspiration Library...")
        add_blocks_to_page(INSPIRATION_LIBRARY_ID, blocks)
        
        print(f"\n🎉 SUCCESS! Studio Dado entry added to Inspiration Library")
        print(f"📊 Blocks added: {len(blocks)}")
        print(f"🏷️  Tags: branding, identity, studio, portfolio, case-study")
        print(f"📄 View library: https://notion.so/{INSPIRATION_LIBRARY_ID}")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()