#!/usr/bin/env python3
"""
Create the Brand & Content System Architecture project - FIXED VERSION
"""

import json
import requests
import os
from datetime import datetime

NOTION_KEY_PATH = "/home/clawd/secrets/notion/api_key"
NOTION_API = "https://api.notion.com/v1"
NOTION_VERSION = "2022-06-28"
PROJECTS_DB_ID = "2f0330c2-8646-8111-9d86-dc9ad729ce37"

def get_notion_key():
    with open(NOTION_KEY_PATH) as f:
        return f.read().strip()

def notion_headers():
    return {
        "Authorization": f"Bearer {get_notion_key()}",
        "Notion-Version": NOTION_VERSION,
        "Content-Type": "application/json"
    }

def create_project_page():
    """Create a page in the Projects database."""
    print("Creating Brand & Content System Architecture project...")
    
    payload = {
        "parent": {"database_id": PROJECTS_DB_ID},
        "properties": {
            "Name": {
                "title": [{"text": {"content": "Brand & Content System Architecture"}}]
            },
            "Status": {"select": {"name": "Active"}},
            "Area": {"select": {"name": "Business"}},
            "Owner": {"select": {"name": "Assaf"}},
            "Priority": {"select": {"name": "🔴 High"}}
        }
    }
    
    try:
        response = requests.post(f"{NOTION_API}/pages", headers=notion_headers(), json=payload)
        
        if response.status_code == 200:
            page_data = response.json()
            print(f"✅ Created project page: {page_data['id']}")
            return page_data
        else:
            print(f"❌ Failed: {response.text}")
            return None
            
    except Exception as e:
        print(f"❌ Exception: {e}")
        return None

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)
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"❌ Failed to create {name}: {response.text}")
        raise Exception(f"Failed to create database: {response.text}")

def setup_system_components_db(parent_id):
    """Create System Components database."""
    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 with proper relation configuration."""
    properties = {
        "Phase": {"title": {}},
        "Description": {"rich_text": {}},
        "Start Date": {"date": {}},
        "End Date": {"date": {}},
        "Components": {
            "relation": {
                "database_id": system_components_db_id,
                "single_property": {}
            }
        },
        "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_to_project_page(page_id):
    """Add detailed content sections to the project page."""
    url = f"{NOTION_API}/blocks/{page_id}/children"
    
    sections = [
        {
            "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"}}],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "divider",
            "divider": {}
        },
        {
            "object": "block",
            "type": "heading_2",
            "heading_2": {
                "rich_text": [{"text": {"content": "📋 Project Overview"}}],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Purpose: "}},
                    {"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."}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Target Audience: "}},
                    {"text": {"content": "Brand strategists, content teams, AI implementation specialists, creative directors"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {
                "rich_text": [
                    {"text": {"content": "Deliverable: "}},
                    {"text": {"content": "Production-ready system architecture with implementation roadmap"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "heading_2",
            "heading_2": {
                "rich_text": [{"text": {"content": "🏗️ Master Databases"}}],
                "color": "default"
            }
        },
        {
            "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:"}}],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "System Components - Track all architectural components, tools, and engines with dependencies and ownership"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "Implementation Roadmap - Manage project phases, timelines, prerequisites, and success criteria"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "Content Templates - Store brand-specific content templates with AI prompts and cultural considerations"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "bulleted_list_item",
            "bulleted_list_item": {
                "rich_text": [
                    {"text": {"content": "Process Workflows - Define content creation and review processes with automation levels and quality gates"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "heading_2",
            "heading_2": {
                "rich_text": [{"text": {"content": "🎯 Core Principles"}}],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Human-AI Collaboration: AI augments human creativity, never replaces it"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Cultural Preservation: Maintain brand soul and cultural awareness"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Scalable Flexibility: Adaptable to various brand archetypes and markets"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Quality Control: Multiple validation layers for brand consistency"}}
                ],
                "color": "default"
            }
        },
        {
            "object": "block",
            "type": "numbered_list_item",
            "numbered_list_item": {
                "rich_text": [
                    {"text": {"content": "Continuous Learning: System evolves with brand and market changes"}}
                ],
                "color": "default"
            }
        }
    ]
    
    payload = {"children": sections}
    response = requests.patch(url, headers=notion_headers(), json=payload)
    
    if response.status_code != 200:
        print(f"❌ Failed to add content: {response.text}")
    else:
        print("✅ Added content sections to project page")

def main():
    print("🚀 Creating Brand & Content System Architecture in Notion")
    print("=" * 60)
    
    try:
        # Step 1: Create project page
        project_page = create_project_page()
        
        if not project_page:
            print("❌ Failed to create project page. Aborting.")
            return
        
        project_page_id = project_page["id"]
        
        # Step 2: Add content to project page
        print("2️⃣ Adding content to project page...")
        add_content_to_project_page(project_page_id)
        
        # Step 3: Create System Components database
        print("3️⃣ Creating System Components database...")
        system_components_db = setup_system_components_db(project_page_id)
        system_components_db_id = system_components_db["id"]
        print(f"   ✅ System Components DB: {system_components_db_id}")
        
        # Step 4: Create Implementation Roadmap database
        print("4️⃣ Creating Implementation Roadmap database...")
        implementation_db = setup_implementation_roadmap_db(project_page_id, system_components_db_id)
        implementation_db_id = implementation_db["id"]
        print(f"   ✅ Implementation Roadmap DB: {implementation_db_id}")
        
        # Step 5: Create Content Templates database
        print("5️⃣ Creating Content Templates database...")
        content_templates_db = setup_content_templates_db(project_page_id)
        content_templates_db_id = content_templates_db["id"]
        print(f"   ✅ Content Templates DB: {content_templates_db_id}")
        
        # Step 6: Create Process Workflows database
        print("6️⃣ Creating Process Workflows database...")
        workflows_db = setup_process_workflows_db(project_page_id)
        workflows_db_id = workflows_db["id"]
        print(f"   ✅ Process Workflows DB: {workflows_db_id}")
        
        print("\n🎉 SUCCESS! Brand & Content System Architecture project created!")
        print("\n📊 Project Summary:")
        print(f"📄 Project Page ID: {project_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 project information
        project_info = {
            "project_page_id": project_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(),
            "project_name": "Brand & Content System Architecture",
            "status": "Successfully created with all databases and properties"
        }
        
        with open("brand_content_project_final.json", "w") as f:
            json.dump(project_info, f, indent=2)
        
        print(f"\n💾 Project information saved to brand_content_project_final.json")
        print("\n✨ The complete Brand & Content System Architecture project is now ready!")
        print("📋 All four master databases have been created with the exact properties from the playbook:")
        print("   • System Components with dependencies tracking")
        print("   • Implementation Roadmap linked to System Components")
        print("   • Content Templates with cultural considerations and AI prompts")
        print("   • Process Workflows with automation levels and quality gates")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()