#!/usr/bin/env python3
"""
Sync curated taste board items to Notion Inspiration Library.
Only syncs items with status='liked' that have URLs.
"""

import json
import os
import re
import requests
from pathlib import Path

# Config
NOTION_KEY = Path('/home/clawd/secrets/notion/api_key').read_text().strip()
NOTION_DB_ID = '2ff330c2-8646-81f0-bbd9-ec474393d7a5'  # Inspiration Library
STATE_FILE = '/home/clawd/workspace/public/taste/state.json'
INDEX_FILE = '/home/clawd/workspace/public/taste/index.html'

HEADERS = {
    'Authorization': f'Bearer {NOTION_KEY}',
    'Notion-Version': '2022-06-28',
    'Content-Type': 'application/json'
}

# Valid taste tags -> Notion multi-select
TAG_MAP = {
    'color': 'colorful',
    'type': 'typography',
    'illustration': 'illustration',
    'photo': 'photography',
    'brand': 'branding',
    '3d': '3D',
    'motion': 'animation',
    'website': 'web design',
    'minimal': 'minimalist',
    'bold': 'bold',
    'editorial': 'editorial',
    'food': 'food',
    'product': 'product photography',
    'texture': 'texture',
    'geometric': 'geometric',
    'layout': 'layout'
}


def load_state():
    """Load current taste board state."""
    with open(STATE_FILE) as f:
        return json.load(f)


def extract_candidates_from_html():
    """Parse index.html to get CANDIDATES array."""
    with open(INDEX_FILE) as f:
        html = f.read()
    
    # Find the CANDIDATES array in the script
    match = re.search(r'const CANDIDATES = \[([\s\S]*?)\];', html)
    if not match:
        print("❌ Could not find CANDIDATES array in index.html")
        return []
    
    array_content = match.group(1)
    candidates = []
    
    # Parse each object line by line using regex
    object_pattern = r'\{\s*id:\s*(\d+),\s*img:\s*[\'"]([^"\']*)[\'"],\s*title:\s*[\'"]([^"\']*)[\'"],\s*desc:\s*[\'"]([^"\']*)[\'"],\s*url:\s*[\'"]([^"\']*)[\'"],\s*source:\s*[\'"]([^"\']*)[\'"]'
    
    for match in re.finditer(object_pattern, array_content):
        candidates.append({
            'id': match.group(1),
            'image': match.group(2),
            'title': match.group(3),
            'desc': match.group(4),
            'url': match.group(5),
            'source': match.group(6)
        })
    
    return candidates


def get_curated_items():
    """Get items that are liked and have URLs."""
    state = load_state()
    candidates = extract_candidates_from_html()
    
    curated = []
    for candidate in candidates:
        item_id = str(candidate.get('id', ''))
        item_state = state.get('items', {}).get(item_id, {})
        
        if item_state.get('status') == 'liked':
            url = candidate.get('url') or candidate.get('source')
            if url:
                curated.append({
                    'id': item_id,
                    'title': candidate.get('title', ''),
                    'url': url,
                    'image': candidate.get('image', ''),
                    'tags': item_state.get('tags', [])
                })
    
    return curated


def check_exists_in_notion(url: str) -> bool:
    """Check if URL already exists in Notion DB."""
    response = requests.post(
        f'https://api.notion.com/v1/databases/{NOTION_DB_ID}/query',
        headers=HEADERS,
        json={
            'filter': {
                'property': 'Link',
                'url': {'equals': url}
            },
            'page_size': 1
        }
    )
    
    if response.status_code == 200:
        data = response.json()
        return len(data.get('results', [])) > 0
    return False


def add_to_notion(item: dict) -> bool:
    """Add item to Notion Inspiration Library."""
    # Map tags to Notion format
    notion_tags = []
    for tag in item.get('tags', []):
        mapped = TAG_MAP.get(tag, tag)
        notion_tags.append({'name': mapped})
    
    # Add 'curated' tag to mark taste board origin
    notion_tags.append({'name': 'taste-board'})
    
    # Build image URL
    image_url = None
    if item.get('image'):
        image_path = item['image']
        if image_path.startswith('../'):
            image_path = image_path.replace('../', '')
        image_url = f"https://curiousendeavor.com/{image_path}"
    
    payload = {
        'parent': {'database_id': NOTION_DB_ID},
        'properties': {
            'Name': {
                'title': [{'text': {'content': item.get('title', 'Untitled')[:100]}}]
            },
            'Link': {
                'url': item.get('url')
            },
            'Tags': {
                'multi_select': notion_tags[:10]  # Notion limit
            },
            'Source Board': {
                'select': {'name': 'CE Taste Board'}
            }
        }
    }
    
    # Add cover image if available
    if image_url:
        payload['cover'] = {
            'type': 'external',
            'external': {'url': image_url}
        }
    
    response = requests.post(
        'https://api.notion.com/v1/pages',
        headers=HEADERS,
        json=payload
    )
    
    if response.status_code in (200, 201):
        return True
    else:
        print(f"  ❌ Notion error: {response.status_code} - {response.text[:200]}")
        return False


def main():
    print("🔄 Syncing taste board to Notion...")
    
    curated = get_curated_items()
    print(f"📋 Found {len(curated)} curated items with URLs")
    
    synced = 0
    skipped = 0
    failed = 0
    
    for item in curated:
        title = item.get('title', 'Untitled')[:50]
        url = item.get('url', '')
        
        # Check if already in Notion
        if check_exists_in_notion(url):
            print(f"  ⏭️  Skip (exists): {title}")
            skipped += 1
            continue
        
        # Add to Notion
        if add_to_notion(item):
            print(f"  ✅ Added: {title}")
            synced += 1
        else:
            print(f"  ❌ Failed: {title}")
            failed += 1
    
    print(f"\n📊 Results:")
    print(f"   Synced: {synced}")
    print(f"   Skipped (existing): {skipped}")
    print(f"   Failed: {failed}")


if __name__ == '__main__':
    main()
