#!/usr/bin/env python3
"""
Create Notion "Rivet Ideas" database for autonomous idea generation and approval workflow.
"""

import json
import os
import requests
from datetime import datetime

# Configuration
NOTION_API_KEY = os.environ.get('NOTION_API_KEY')
PARENT_PAGE_ID = os.environ.get('NOTION_PARENT_PAGE_ID')  # Optional: if you want to create under a specific page

# Database structure
DATABASE_NAME = "Rivet Ideas"

# Properties definition
properties = {
    "Title": {
        "title": {}
    },
    "Status": {
        "select": {
            "options": [
                {"name": "Approved", "color": "green"},
                {"name": "Plan", "color": "yellow"},
                {"name": "In Progress", "color": "blue"},
                {"name": "Done", "color": "gray"}
            ]
        }
    },
    "Priority": {
        "select": {
            "options": [
                {"name": "High", "color": "red"},
                {"name": "Medium", "color": "yellow"},
                {"name": "Low", "color": "gray"}
            ]
        }
    },
    "Category": {
        "rich_text": {}
    },
    "Description": {
        "rich_text": {}
    },
    "Date Added": {
        "date": {}
    },
    "Autonomous": {
        "select": {
            "options": [
                {"name": "Yes", "color": "green"},
                {"name": "No", "color": "red"}
            ]
        }
    }
}

def create_database():
    """Create the Rivet Ideas database in Notion."""
    
    if not NOTION_API_KEY:
        print("Error: NOTION_API_KEY environment variable is required")
        return None
    
    # API endpoint
    url = "https://api.notion.com/v1/databases"
    
    # Headers
    headers = {
        "Authorization": f"Bearer {NOTION_API_KEY}",
        "Content-Type": "application/json",
        "Notion-Version": "2022-06-28"
    }
    
    # Request payload
    payload = {
        "parent": {
            "type": "page_id",
            "page_id": PARENT_PAGE_ID if PARENT_PAGE_ID else ""
        },
        "title": [
            {
                "type": "text",
                "text": {
                    "content": DATABASE_NAME
                }
            }
        ],
        "properties": properties
    }
    
    # If no parent page ID provided, create in the workspace root
    if not PARENT_PAGE_ID:
        # Get the first available page to use as parent
        pages_url = "https://api.notion.com/v1/search"
        pages_response = requests.post(
            pages_url,
            headers=headers,
            json={"filter": {"property": "object", "value": "page"}}
        )
        
        if pages_response.status_code == 200:
            pages = pages_response.json().get("results", [])
            if pages:
                payload["parent"]["page_id"] = pages[0]["id"]
            else:
                print("Error: No pages found in workspace. Please create a page first.")
                return None
        else:
            print(f"Error fetching pages: {pages_response.status_code} - {pages_response.text}")
            return None
    
    # Create the database
    response = requests.post(url, headers=headers, json=payload)
    
    if response.status_code == 200:
        database = response.json()
        print(f"✅ Database '{DATABASE_NAME}' created successfully!")
        print(f"Database ID: {database['id']}")
        print(f"Database URL: {database['url']}")
        
        # Create views configuration
        create_views_config(database['id'])
        
        return database['id']
    else:
        print(f"❌ Error creating database: {response.status_code} - {response.text}")
        return None

def create_views_config(database_id):
    """Create configuration file for views setup."""
    views_config = {
        "database_id": database_id,
        "views": {
            "All Ideas": {
                "type": "table",
                "filter": None
            },
            "Approved Ideas": {
                "type": "table",
                "filter": {
                    "property": "Status",
                    "select": {
                        "equals": "Approved"
                    }
                }
            },
            "High Priority": {
                "type": "table",
                "filter": {
                    "property": "Priority",
                    "select": {
                        "equals": "High"
                    }
                }
            }
        },
        "template": {
            "properties": {
                "Status": {"select": {"name": "Plan"}},
                "Priority": {"select": {"name": "Medium"}},
                "Date Added": {"date": {"start": datetime.now().isoformat()}},
                "Autonomous": {"select": {"name": "No"}}
            }
        }
    }
    
    config_file = "notion_rivet_ideas_config.json"
    with open(config_file, 'w') as f:
        json.dump(views_config, f, indent=2)
    
    print(f"\n📋 Views configuration saved to: {config_file}")
    print("\nTo complete the setup, you'll need to manually create the views in Notion:")
    print("1. Open the database in Notion")
    print("2. Click the '+' next to the default view")
    print("3. Create the following views:")
    print("   - 'All Ideas' (Table view, no filter)")
    print("   - 'Approved Ideas' (Table view, filter: Status = Approved)")
    print("   - 'High Priority' (Table view, filter: Priority = High)")
    print("\n4. To create a template:")
    print("   - Click the arrow next to 'New' button")
    print("   - Select 'New template'")
    print("   - Set default values for Status, Priority, etc.")

def main():
    """Main function."""
    print("🚀 Creating Notion 'Rivet Ideas' database...\n")
    
    # Check for API key
    if not NOTION_API_KEY:
        print("⚠️  Please set the NOTION_API_KEY environment variable")
        print("You can get your API key from: https://www.notion.so/my-integrations")
        print("\nUsage:")
        print("export NOTION_API_KEY='your-integration-token'")
        print("export NOTION_PARENT_PAGE_ID='optional-parent-page-id'")
        print("python3 create_notion_database.py")
        return
    
    # Create the database
    database_id = create_database()
    
    if database_id:
        print("\n✨ Setup complete!")
        print(f"Database ID: {database_id}")
        print("\n📚 Documentation:")
        print("- Database created with all required properties")
        print("- Views need to be created manually in Notion (see instructions above)")
        print("- Configuration saved to notion_rivet_ideas_config.json")
        print("\n🔄 To add ideas programmatically, use the Database ID with the Notion API")

if __name__ == "__main__":
    main()