#!/usr/bin/env python3
"""
Add We Are Motto × Attend case study 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_attend_page() -> Dict[str, Any]:
    """Create a new page in the Inspiration Library database for We Are Motto × Attend."""
    page_data = {
        "parent": {
            "database_id": INSPIRATION_DATABASE_ID
        },
        "properties": {
            "Name": {
                "title": [
                    {
                        "text": {
                            "content": "We Are Motto × Attend — Premium Home Tech Branding"
                        }
                    }
                ]
            },
            "Link": {
                "url": "https://wearemotto.com/portfolio/attend"
            },
            "Tags": {
                "multi_select": [
                    {"name": "brand identity"},
                    {"name": "case study layout"},
                    {"name": "tech branding"},
                    {"name": "warm palette"},
                    {"name": "typography-over-photography"},
                    {"name": "lifestyle positioning"},
                    {"name": "marquee type"},
                    {"name": "toggle UX"},
                    {"name": "Motto"},
                    {"name": "premium"},
                    {"name": "home/lifestyle"}
                ]
            },
            "Source Board": {
                "select": {
                    "name": "visual-input"
                }
            },
            "Use Case": {
                "select": {
                    "name": "Brand Reference"
                }
            },
            "Status": {
                "select": {
                    "name": "Processed"
                }
            },
            "Positioning Lesson": {
                "rich_text": [
                    {
                        "text": {
                            "content": "\"Premium domesticity meets tech sophistication.\" Positions home tech services company not as gadget-forward but warm, architectural, lifestyle-driven — closer to luxury real estate than typical smart home. Technology recedes, human experience advances."
                        }
                    }
                ]
            },
            "Strategic Insight": {
                "rich_text": [
                    {
                        "text": {
                            "content": "Motto transforms typical tech branding through warm neutrals (wood tones, cream, natural light) vs. cool blues/blacks. Hero shows hand interacting with keypad against wood grain — tech as contextual, not dominant. Starburst mark functions as both attention spark and versatile brand device throughout case study system. Submitted by Assaf."
                        }
                    }
                ]
            },
            "Image Count": {
                "number": 3
            }
        },
        "children": [
            {
                "object": "block",
                "type": "heading_2",
                "heading_2": {
                    "rich_text": [{"text": {"content": "Design Strategy"}}]
                }
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": "We Are Motto repositions Attend's home tech services through \"premium domesticity meets tech sophistication\" — making technology feel warm, architectural, and lifestyle-driven rather than gadget-forward."}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "heading_3",
                "heading_3": {
                    "rich_text": [{"text": {"content": "Key Design Techniques"}}]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Typography-over-photography: Infinitely scrolling '✳ ATTEND ✳ ATTEND' marquee in ultra-light weight layered transparently over lifestyle photography"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Warm palette strategy: Wood tones, cream, soft natural light vs typical tech brand cool blues/blacks"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Contextual technology: Hero shows hand + keypad interaction against wood grain — tech present but not dominant"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Systematic brand device: Starburst/asterisk icon functions as attention spark and versatile punctuation throughout case study"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "heading_3",
                "heading_3": {
                    "rich_text": [{"text": {"content": "Case Study Layout Innovation"}}]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Visual/Reading view toggle: Thoughtful UX acknowledging both visual browsers and strategy-focused readers"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Alternating rhythm: Text-heavy strategy sections with metadata alternating with full-bleed/grid image sections"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {
                    "rich_text": [
                        {"text": {"content": "Geometric sans-serif at extreme scale in thin/light weight — confidence of ultra-thin at massive size over photography"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "heading_3",
                "heading_3": {
                    "rich_text": [{"text": {"content": "Brand Positioning"}}]
                }
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": "\"A home tech services company transforming the way people experience and maintain home ownership.\" Attend isn't selling hardware — they're selling effortless home ownership feeling."}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "divider",
                "divider": {}
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": f"Visual references captured: hero marquee treatment, full case study layout, curated crop focusing on starburst + ATTEND wordmark over warm textures. 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 We Are Motto × Attend 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 We Are Motto × Attend case study to Notion Inspiration Library")
    print("=" * 70)
    
    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 Attend case study entry data...")
        page_data = create_attend_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! We Are Motto × Attend entry added to Inspiration Library")
        print(f"🏷️  Key tags: brand identity, tech branding, warm palette, typography-over-photography, lifestyle positioning, marquee type")
        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()