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

import json
import requests
import os
from datetime import datetime
from typing import 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 get_database_schema(database_id: str) -> Dict[str, Any]:
    """Get database schema to understand available properties."""
    url = f"{NOTION_API}/databases/{database_id}"
    response = requests.get(url, headers=notion_headers())
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error fetching database schema: {response.status_code}")
        print(f"Response: {response.text}")
        return {}

def create_studio_dado_entry(database_schema: Dict[str, Any]) -> Dict[str, Any]:
    """Create the database entry for Studio Dado."""
    
    # Get available properties from the database schema
    properties = database_schema.get('properties', {})
    print("   📋 Available database properties:")
    for prop_name, prop_info in properties.items():
        print(f"      - {prop_name}: {prop_info.get('type', 'unknown')}")
    
    # Create the entry based on common database property patterns
    entry_properties = {}
    
    # Title/Name property (usually the first title property)
    title_props = [prop for prop, info in properties.items() if info.get('type') == 'title']
    if title_props:
        title_prop = title_props[0]
        entry_properties[title_prop] = {
            "title": [{"text": {"content": "Studio Dado — We Are Motto"}}]
        }
    
    # Rich text properties for description
    rich_text_props = [prop for prop, info in properties.items() if info.get('type') == 'rich_text']
    if rich_text_props:
        desc_prop = rich_text_props[0]  # Use first rich text property
        entry_properties[desc_prop] = {
            "rich_text": [{
                "text": {
                    "content": "Case study showcasing We Are Motto's branding and identity work for Studio Dado. Portfolio piece demonstrating contemporary studio identity systems and brand architecture."
                }
            }]
        }
    
    # URL property
    url_props = [prop for prop, info in properties.items() if info.get('type') == 'url']
    if url_props:
        url_prop = url_props[0]
        entry_properties[url_prop] = {
            "url": "https://wearemotto.com/portfolio/studio-dado"
        }
    
    # Tags/Multi-select property
    multiselect_props = [prop for prop, info in properties.items() if info.get('type') == 'multi_select']
    if multiselect_props:
        tags_prop = multiselect_props[0]
        entry_properties[tags_prop] = {
            "multi_select": [
                {"name": "branding"},
                {"name": "identity"},
                {"name": "studio"},
                {"name": "portfolio"},
                {"name": "case-study"}
            ]
        }
    
    # Select property (single select)
    select_props = [prop for prop, info in properties.items() if info.get('type') == 'select']
    if select_props:
        category_prop = select_props[0]
        entry_properties[category_prop] = {
            "select": {"name": "branding"}
        }
    
    # Date property
    date_props = [prop for prop, info in properties.items() if info.get('type') == 'date']
    if date_props:
        date_prop = date_props[0]
        entry_properties[date_prop] = {
            "date": {"start": datetime.now().strftime("%Y-%m-%d")}
        }
    
    # People property for submitted by
    people_props = [prop for prop, info in properties.items() if info.get('type') == 'people']
    if people_props:
        # We don't have user IDs, so skip this for now
        pass
    
    return {
        "parent": {"database_id": INSPIRATION_DATABASE_ID},
        "properties": entry_properties
    }

def add_entry_to_database(database_id: str, entry_data: Dict[str, Any]) -> bool:
    """Add new entry to the Notion database."""
    url = f"{NOTION_API}/pages"
    
    print(f"   📝 Adding entry with properties: {list(entry_data['properties'].keys())}")
    
    try:
        response = requests.post(url, headers=notion_headers(), json=entry_data)
        
        if response.status_code == 200:
            result = response.json()
            page_id = result.get('id', '')
            print(f"   ✅ Successfully created entry: {page_id}")
            return True
        else:
            print(f"   ❌ Error creating entry: {response.status_code}")
            print(f"   Response: {response.text}")
            return False
            
    except Exception as e:
        print(f"   ❌ Exception: {e}")
        return False

def main():
    print("📌 Adding Studio Dado to Notion Inspiration Database")
    print("=" * 52)
    
    try:
        # Step 1: Get database schema
        print("1️⃣ Fetching database schema...")
        schema = get_database_schema(INSPIRATION_DATABASE_ID)
        if not schema:
            print("❌ Cannot access database schema. Exiting.")
            return
        
        db_title = schema.get('title', [{}])[0].get('plain_text', 'Unknown')
        print(f"   ✅ Database found: {db_title}")
        
        # Step 2: Create entry data
        print("2️⃣ Creating Studio Dado entry data...")
        entry_data = create_studio_dado_entry(schema)
        print(f"   ✅ Entry prepared with {len(entry_data['properties'])} properties")
        
        # Step 3: Add to database
        print("3️⃣ Adding to Notion Inspiration Database...")
        success = add_entry_to_database(INSPIRATION_DATABASE_ID, entry_data)
        
        if success:
            print(f"\n🎉 SUCCESS! Studio Dado entry added to Inspiration Database")
            print(f"🏷️  Tags: branding, identity, studio, portfolio, case-study")
            print(f"🔗 URL: https://wearemotto.com/portfolio/studio-dado")
            print(f"👤 Submitted by: Assaf (via #visual-input)")
            print(f"📄 View database: https://notion.so/{INSPIRATION_DATABASE_ID}")
        else:
            print(f"\n❌ FAILED to add entry to database")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()