#!/usr/bin/env python3
"""
Add Smack Bang Designs to Notion Inspiration Library.
Creates a new database entry with proper schema.
"""

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_DATABASE_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_smackbang_page() -> Dict[str, Any]:
    """Create a new page in the Inspiration Library database for Smack Bang."""
    page_data = {
        "parent": {
            "database_id": INSPIRATION_DATABASE_ID
        },
        "properties": {
            "Name": {
                "title": [
                    {
                        "text": {
                            "content": "Smack Bang Designs — Independent Creative Agency"
                        }
                    }
                ]
            },
            "Link": {
                "url": "https://smackbang.co/"
            },
            "Tags": {
                "multi_select": [
                    {"name": "branding"},
                    {"name": "agency"},
                    {"name": "independent-studio"},
                    {"name": "color-confident"},
                    {"name": "premium"},
                    {"name": "typography"},
                    {"name": "art-direction"},
                    {"name": "portfolio"},
                    {"name": "warm-palette"}
                ]
            },
            "Source Board": {
                "select": {
                    "name": "visual-input"
                }
            },
            "Use Case": {
                "select": {
                    "name": "Brand Reference"
                }
            },
            "Status": {
                "select": {
                    "name": "Processed"
                }
            },
            "Positioning Lesson": {
                "rich_text": [
                    {
                        "text": {
                            "content": "\"We are an independent creative agency fuelling the flames of connection.\" Positions as premium studio for next-gen ventures and legacy brands ready to reimagine connection. Demonstrates bold color confidence, sophisticated art direction, and typography-driven brand identity."
                        }
                    }
                ]
            },
            "Strategic Insight": {
                "rich_text": [
                    {
                        "text": {
                            "content": "Strong portfolio showcasing color confidence through projects like DOPHA (terracotta/plum luxury interiors) and DEUCE (tennis lifestyle brand). Visual characteristics include warm palettes, textural richness, premium materiality, and cinema-quality lifestyle photography. Submitted by Assaf."
                        }
                    }
                ]
            },
            "Image Count": {
                "number": 4
            }
        },
        "children": [
            {
                "object": "block",
                "type": "heading_2",
                "heading_2": {
                    "rich_text": [{"text": {"content": "Agency Overview"}}]
                }
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": "Independent creative agency focused on connection and bold brand building. Work spans next-gen ventures and legacy brands ready to reimagine their approach."}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "heading_3",
                "heading_3": {
                    "rich_text": [{"text": {"content": "Featured Projects"}}]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "DOPHA - Rebels of reinvention - Rich terracotta/plum palette, premium interiors branding"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "DEUCE - The new rules of the court - Tennis-inspired lifestyle brand with vintage club aesthetic"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Alta Mesa - A new language of wellness hospitality"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Nalia - Turning cultural celebration into cult status"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "heading_3",
                "heading_3": {
                    "rich_text": [{"text": {"content": "Visual DNA"}}]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Color confidence: Bold, warm palettes (terracotta, plum, amber)"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Typography: Refined serif/sans-serif pairings with high contrast"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Art direction: Textural richness, premium materiality"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Photography: Lifestyle-focused, aspirational, cinema-quality"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "divider",
                "divider": {}
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": f"Visual references captured from homepage, DOPHA project (strongest brand demo), DEUCE project, and projects overview. Added {datetime.now().strftime('%Y-%m-%d %H:%M UTC')} by Jessica (subagent)."}}
                    ]
                }
            }
        ]
    }
    
    return page_data

def verify_database_exists(database_id: str) -> bool:
    """Verify that the target database exists and is accessible."""
    url = f"{NOTION_API}/databases/{database_id}"
    print(f"   🔍 Checking database: {url}")
    
    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}")
        return False
    
    database_data = response.json()
    database_title = database_data.get('title', [{}])[0].get('plain_text', 'Unknown')
    print(f"   ✅ Database found: {database_title}")
    return True

def create_page_in_database(page_data: Dict[str, Any]) -> None:
    """Create a new page in the Notion database."""
    url = f"{NOTION_API}/pages"
    
    print("Creating new page in Inspiration Library...")
    
    try:
        response = requests.post(url, headers=notion_headers(), json=page_data)
        
        if response.status_code == 200:
            page_response = response.json()
            page_id = page_response.get('id', '')
            page_url = page_response.get('url', '')
            print(f"✅ Successfully created Smack Bang entry in Inspiration Library")
            print(f"   📄 Page ID: {page_id}")
            print(f"   🔗 Page URL: {page_url}")
        else:
            print(f"❌ Error: {response.status_code}")
            print(f"Response: {response.text}")
                    
    except Exception as e:
        print(f"Exception: {e}")

def main():
    print("📌 Adding Smack Bang Designs to Notion Inspiration Library")
    print("=" * 60)
    
    try:
        # Step 1: Verify database exists
        print("1️⃣ Verifying Inspiration Library database access...")
        if not verify_database_exists(INSPIRATION_DATABASE_ID):
            print("❌ Cannot access Inspiration Library database. Exiting.")
            return
        
        # Step 2: Create page data
        print("2️⃣ Creating Smack Bang entry data...")
        page_data = create_smackbang_page()
        print(f"   ✅ Created page data with {len(page_data['children'])} content blocks")
        
        # Step 3: Add to Notion
        print("3️⃣ Adding to Notion Inspiration Library...")
        create_page_in_database(page_data)
        
        print(f"\n🎉 SUCCESS! Smack Bang entry added to Inspiration Library")
        print(f"🏷️  Tags: branding, agency, independent-studio, color-confident, premium, typography, art-direction, portfolio, warm-palette")
        print(f"📄 View database: https://notion.so/{INSPIRATION_DATABASE_ID}")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()