#!/usr/bin/env python3
"""
Set up the complete Brand & Content System Architecture project in Notion.
Creates the main project page and 4 master databases with all specified properties.
"""

import json
import requests
import os
from datetime import datetime

# Configuration
NOTION_KEY_PATH = "/home/clawd/secrets/notion/api_key"
NOTION_API = "https://api.notion.com/v1"
NOTION_VERSION = "2022-06-28"

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_main_page():
    """Create the main project page."""
    url = f"{NOTION_API}/pages"
    
    # Get the workspace (parent)
    parent_response = requests.get(f"{NOTION_API}/search", headers=notion_headers(), json={"filter": {"value": "database", "property": "object"}})
    
    # Use the workspace as parent (empty parent for workspace-level page)
    payload = {
        "parent": {"type": "page_id", "page_id": "e57976e8-c3be-4e44-a82d-fd8c14e74e12"},  # Replace with actual workspace ID
        "properties": {
            "title": [{"text": {"content": "Brand & Content System Architecture"}}]
        },
        "children": [
            {
                "object": "block",
                "type": "heading_1",
                "heading_1": {
                    "rich_text": [{"text": {"content": "Brand & Content System Architecture Playbook"}}]
                }
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [{"text": {"content": "A comprehensive guide for building AI-powered brand systems that maintain creative soul and cultural awareness", "annotations": {"italic": True}}}]
                }
            },
            {
                "object": "block",
                "type": "divider",
                "divider": {}
            },
            {
                "object": "block",
                "type": "heading_2",
                "heading_2": {
                    "rich_text": [{"text": {"content": "📋 Project Overview"}}]
                }
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": "Purpose: ", "annotations": {"bold": True}}},
                        {"text": {"content": "Create scalable, AI-enhanced brand and content systems that preserve human creativity, cultural nuance, and authentic brand voice while leveraging automation for efficiency."}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": "Target Audience: ", "annotations": {"bold": True}}},
                        {"text": {"content": "Brand strategists, content teams, AI implementation specialists, creative directors"}}
                    ]
                }
            },
            {
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [
                        {"text": {"content": "Deliverable: ", "annotations": {"bold": True}}},
                        {"text": {"content": "Production-ready system architecture with implementation roadmap"}}
                    ]
                }
            }
        ]
    }
    
    # Try creating as a workspace-level page (without explicit parent)
    try:
        payload_workspace = {
            "parent": {"type": "workspace"},
            "properties": {
                "title": [{"text": {"content": "Brand & Content System Architecture"}}]
            },
            "children": payload["children"]
        }
        response = requests.post(url, headers=notion_headers(), json=payload_workspace)
        if response.status_code == 200:
            return response.json()
    except:
        pass
    
    # Fallback: try to create without specifying parent
    payload_simple = {
        "parent": {"type": "workspace"},
        "properties": {
            "title": [{"text": {"content": "Brand & Content System Architecture"}}]
        }
    }
    
    response = requests.post(url, headers=notion_headers(), json=payload_simple)
    response.raise_for_status()
    return response.json()

def create_database(parent_id, name, properties):
    """Create a database with specified properties."""
    url = f"{NOTION_API}/databases"
    
    payload = {
        "parent": {"type": "page_id", "page_id": parent_id},
        "title": [{"type": "text", "text": {"content": name}}],
        "properties": properties
    }
    
    response = requests.post(url, headers=notion_headers(), json=payload)
    response.raise_for_status()
    return response.json()

def setup_system_components_db(parent_id):
    """Create System Components database with all required properties."""
    properties = {
        "Component Name": {
            "title": {}
        },
        "Type": {
            "select": {
                "options": [
                    {"name": "Architecture", "color": "blue"},
                    {"name": "Content", "color": "green"},
                    {"name": "Process", "color": "yellow"},
                    {"name": "Engine", "color": "red"},
                    {"name": "Tool", "color": "purple"}
                ]
            }
        },
        "Status": {
            "select": {
                "options": [
                    {"name": "Planned", "color": "gray"},
                    {"name": "In Development", "color": "yellow"},
                    {"name": "Testing", "color": "orange"},
                    {"name": "Production", "color": "green"},
                    {"name": "Deprecated", "color": "red"}
                ]
            }
        },
        "Priority": {
            "select": {
                "options": [
                    {"name": "Critical", "color": "red"},
                    {"name": "High", "color": "orange"},
                    {"name": "Medium", "color": "yellow"},
                    {"name": "Low", "color": "gray"}
                ]
            }
        },
        "Owner": {
            "people": {}
        },
        "Documentation": {
            "url": {}
        },
        "Last Updated": {
            "date": {}
        },
        "Tags": {
            "multi_select": {
                "options": [
                    {"name": "AI", "color": "blue"},
                    {"name": "Culture", "color": "green"},
                    {"name": "Brand", "color": "red"},
                    {"name": "Automation", "color": "purple"},
                    {"name": "Quality", "color": "orange"}
                ]
            }
        }
    }
    
    return create_database(parent_id, "System Components", properties)

def setup_implementation_roadmap_db(parent_id, system_components_db_id):
    """Create Implementation Roadmap database."""
    properties = {
        "Phase": {
            "title": {}
        },
        "Description": {
            "rich_text": {}
        },
        "Start Date": {
            "date": {}
        },
        "End Date": {
            "date": {}
        },
        "Components": {
            "relation": {
                "database_id": system_components_db_id
            }
        },
        "Prerequisites": {
            "rich_text": {}
        },
        "Success Criteria": {
            "rich_text": {}
        },
        "Resources Required": {
            "rich_text": {}
        },
        "Status": {
            "select": {
                "options": [
                    {"name": "Planning", "color": "gray"},
                    {"name": "Active", "color": "yellow"},
                    {"name": "Complete", "color": "green"},
                    {"name": "Blocked", "color": "red"}
                ]
            }
        }
    }
    
    return create_database(parent_id, "Implementation Roadmap", properties)

def setup_content_templates_db(parent_id):
    """Create Content Templates database."""
    properties = {
        "Template Name": {
            "title": {}
        },
        "Content Type": {
            "select": {
                "options": [
                    {"name": "Social", "color": "blue"},
                    {"name": "Blog", "color": "green"},
                    {"name": "Email", "color": "yellow"},
                    {"name": "Video", "color": "red"},
                    {"name": "Audio", "color": "purple"},
                    {"name": "Visual", "color": "orange"}
                ]
            }
        },
        "Brand Archetype": {
            "select": {
                "options": [
                    {"name": "Innovator", "color": "blue"},
                    {"name": "Sage", "color": "purple"},
                    {"name": "Explorer", "color": "green"},
                    {"name": "Hero", "color": "red"},
                    {"name": "Creator", "color": "orange"},
                    {"name": "Caregiver", "color": "pink"}
                ]
            }
        },
        "Tone Requirements": {
            "multi_select": {
                "options": [
                    {"name": "Professional", "color": "blue"},
                    {"name": "Casual", "color": "green"},
                    {"name": "Friendly", "color": "yellow"},
                    {"name": "Authoritative", "color": "red"},
                    {"name": "Inspirational", "color": "purple"},
                    {"name": "Educational", "color": "orange"}
                ]
            }
        },
        "Cultural Considerations": {
            "rich_text": {}
        },
        "AI Prompts": {
            "rich_text": {}
        },
        "Human Review Points": {
            "rich_text": {}
        },
        "Template File": {
            "files": {}
        }
    }
    
    return create_database(parent_id, "Content Templates", properties)

def setup_process_workflows_db(parent_id):
    """Create Process Workflows database."""
    properties = {
        "Workflow Name": {
            "title": {}
        },
        "Process Stage": {
            "select": {
                "options": [
                    {"name": "Ideation", "color": "blue"},
                    {"name": "Creation", "color": "green"},
                    {"name": "Review", "color": "yellow"},
                    {"name": "Approval", "color": "orange"},
                    {"name": "Distribution", "color": "red"}
                ]
            }
        },
        "Automation Level": {
            "select": {
                "options": [
                    {"name": "Full", "color": "green"},
                    {"name": "Partial", "color": "yellow"},
                    {"name": "Manual Override", "color": "orange"},
                    {"name": "Human-First", "color": "red"}
                ]
            }
        },
        "Cultural Checkpoints": {
            "rich_text": {}
        },
        "Quality Gates": {
            "rich_text": {}
        },
        "Feedback Loops": {
            "rich_text": {}
        },
        "SOP Document": {
            "files": {}
        }
    }
    
    return create_database(parent_id, "Process Workflows", properties)

def add_content_sections(page_id):
    """Add the main content sections to the project page."""
    url = f"{NOTION_API}/blocks/{page_id}/children"
    
    sections = [
        {
            "object": "block",
            "type": "heading_2",
            "heading_2": {
                "rich_text": [{"text": {"content": "🏗️ Master Databases"}}]
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [{"text": {"content": "This project includes four interconnected master databases designed to manage the complete brand content system architecture:"}}]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "System Components", "annotations": {"bold": True}}},
                    {"text": {"content": " - Track all architectural components, tools, and engines"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "Implementation Roadmap", "annotations": {"bold": True}}},
                    {"text": {"content": " - Manage project phases, timelines, and dependencies"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "Content Templates", "annotations": {"bold": True}}},
                    {"text": {"content": " - Store brand-specific content templates with AI prompts"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "Process Workflows", "annotations": {"bold": True}}},
                    {"text": {"content": " - Define and manage content creation and review processes"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "heading_2",
            "heading_2": {
                "rich_text": [{"text": {"content": "🎯 Core Principles"}}]
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Human-AI Collaboration: ", "annotations": {"bold": True}}},
                    {"text": {"content": "AI augments human creativity, never replaces it"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Cultural Preservation: ", "annotations": {"bold": True}}},
                    {"text": {"content": "Maintain brand soul and cultural awareness"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Scalable Flexibility: ", "annotations": {"bold": True}}},
                    {"text": {"content": "Adaptable to various brand archetypes and markets"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Quality Control: ", "annotations": {"bold": True}}},
                    {"text": {"content": "Multiple validation layers for brand consistency"}}
                ]
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Continuous Learning: ", "annotations": {"bold": True}}},
                    {"text": {"content": "System evolves with brand and market changes"}}
                ]
            }
        }
    ]
    
    payload = {"children": sections}
    response = requests.patch(url, headers=notion_headers(), json=payload)
    response.raise_for_status()
    return response.json()

def main():
    print("🚀 Setting up Brand & Content System Architecture in Notion")
    print("=" * 60)
    
    try:
        # Step 1: Create main project page
        print("1️⃣ Creating main project page...")
        main_page = create_main_page()
        main_page_id = main_page["id"]
        print(f"   ✅ Created page: {main_page_id}")
        
        # Step 2: Create System Components database
        print("2️⃣ Creating System Components database...")
        system_components_db = setup_system_components_db(main_page_id)
        system_components_db_id = system_components_db["id"]
        print(f"   ✅ Created database: {system_components_db_id}")
        
        # Step 3: Create Implementation Roadmap database (with relation to System Components)
        print("3️⃣ Creating Implementation Roadmap database...")
        implementation_db = setup_implementation_roadmap_db(main_page_id, system_components_db_id)
        implementation_db_id = implementation_db["id"]
        print(f"   ✅ Created database: {implementation_db_id}")
        
        # Step 4: Create Content Templates database
        print("4️⃣ Creating Content Templates database...")
        content_templates_db = setup_content_templates_db(main_page_id)
        content_templates_db_id = content_templates_db["id"]
        print(f"   ✅ Created database: {content_templates_db_id}")
        
        # Step 5: Create Process Workflows database
        print("5️⃣ Creating Process Workflows database...")
        workflows_db = setup_process_workflows_db(main_page_id)
        workflows_db_id = workflows_db["id"]
        print(f"   ✅ Created database: {workflows_db_id}")
        
        # Step 6: Add content sections to main page
        print("6️⃣ Adding content sections to main page...")
        add_content_sections(main_page_id)
        print("   ✅ Added content sections")
        
        print("\n🎉 SUCCESS! Brand & Content System Architecture project created in Notion")
        print(f"📄 Main Page ID: {main_page_id}")
        print(f"🗄️ System Components DB: {system_components_db_id}")
        print(f"🗓️ Implementation Roadmap DB: {implementation_db_id}")
        print(f"📝 Content Templates DB: {content_templates_db_id}")
        print(f"⚙️ Process Workflows DB: {workflows_db_id}")
        
        # Save IDs to a file for reference
        project_info = {
            "main_page_id": main_page_id,
            "databases": {
                "system_components": system_components_db_id,
                "implementation_roadmap": implementation_db_id,
                "content_templates": content_templates_db_id,
                "process_workflows": workflows_db_id
            },
            "created_at": datetime.now().isoformat()
        }
        
        with open("brand_content_project_ids.json", "w") as f:
            json.dump(project_info, f, indent=2)
        
        print(f"\n💾 Project IDs saved to brand_content_project_ids.json")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()