#!/usr/bin/env python3
"""Test Notion API connectivity and debug page creation."""

import json
import requests
import os

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():
    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 test_basic_connectivity():
    """Test basic API connectivity."""
    print("Testing basic API connectivity...")
    try:
        response = requests.get(f"{NOTION_API}/users/me", headers=notion_headers())
        print(f"Status: {response.status_code}")
        if response.status_code == 200:
            user_data = response.json()
            print(f"✅ Connected as: {user_data.get('name', 'Unknown')}")
            return True
        else:
            print(f"❌ Error: {response.text}")
            return False
    except Exception as e:
        print(f"❌ Exception: {e}")
        return False

def search_existing_pages():
    """Search for existing pages to understand structure."""
    print("\nSearching for existing pages...")
    try:
        response = requests.post(
            f"{NOTION_API}/search", 
            headers=notion_headers(),
            json={"filter": {"property": "object", "value": "page"}, "page_size": 10}
        )
        print(f"Search status: {response.status_code}")
        if response.status_code == 200:
            results = response.json().get("results", [])
            print(f"Found {len(results)} pages:")
            for page in results[:3]:  # Show first 3
                title = ""
                if page.get("properties", {}).get("title"):
                    title_prop = page["properties"]["title"]
                    if title_prop.get("title"):
                        title = title_prop["title"][0].get("plain_text", "No title")
                elif page.get("properties", {}).get("Name"):
                    name_prop = page["properties"]["Name"]
                    if name_prop.get("title"):
                        title = name_prop["title"][0].get("plain_text", "No title")
                print(f"  - {title} (ID: {page['id']})")
                print(f"    Parent: {page.get('parent', {})}")
            return results
        else:
            print(f"❌ Search error: {response.text}")
            return []
    except Exception as e:
        print(f"❌ Search exception: {e}")
        return []

def try_create_simple_page():
    """Try creating a very simple page."""
    print("\nAttempting to create a simple page...")
    
    # Try creating in workspace root
    payload = {
        "parent": {"type": "workspace", "workspace": True},
        "properties": {
            "title": {
                "title": [{"text": {"content": "Brand & Content System Architecture"}}]
            }
        }
    }
    
    try:
        response = requests.post(f"{NOTION_API}/pages", headers=notion_headers(), json=payload)
        print(f"Create page status: {response.status_code}")
        print(f"Response: {response.text}")
        
        if response.status_code == 200:
            page_data = response.json()
            print(f"✅ Created page: {page_data['id']}")
            return page_data
        else:
            print(f"❌ Failed to create page")
            return None
            
    except Exception as e:
        print(f"❌ Create page exception: {e}")
        return None

def try_create_database_first():
    """Try creating a database directly in the workspace."""
    print("\nAttempting to create database directly in workspace...")
    
    payload = {
        "parent": {"type": "workspace", "workspace": True},
        "title": [{"type": "text", "text": {"content": "Test Database"}}],
        "properties": {
            "Name": {"title": {}},
            "Status": {"select": {"options": [{"name": "Active", "color": "green"}]}}
        }
    }
    
    try:
        response = requests.post(f"{NOTION_API}/databases", headers=notion_headers(), json=payload)
        print(f"Create database status: {response.status_code}")
        print(f"Response: {response.text}")
        
        if response.status_code == 200:
            db_data = response.json()
            print(f"✅ Created database: {db_data['id']}")
            return db_data
        else:
            print(f"❌ Failed to create database")
            return None
            
    except Exception as e:
        print(f"❌ Create database exception: {e}")
        return None

def main():
    print("=" * 50)
    print("Notion API Debug Session")
    print("=" * 50)
    
    # Test basic connectivity
    if not test_basic_connectivity():
        print("❌ Basic connectivity failed. Check API key.")
        return
    
    # Search for existing structure
    existing_pages = search_existing_pages()
    
    # Try different creation approaches
    try_create_simple_page()
    try_create_database_first()

if __name__ == "__main__":
    main()