#!/usr/bin/env python3
"""
Two-way sync for Qualified Sources between Notion and CE site.

Usage:
  python3 sync-sources.py notion-to-site  # Pull approved sources from Notion → update site
  python3 sync-sources.py site-to-notion  # Push pending submissions to Notion
  python3 sync-sources.py status          # Show sync status
"""

import json
import requests
import sys
import os
from pathlib import Path

NOTION_DB_ID = "30e330c2-8646-8183-a237-ec2d07d79fe1"
SOURCES_STATE = Path("/home/clawd/workspace/public/sources/state.json")
SOURCES_HTML = Path("/home/clawd/workspace/public/sources/index.html")

def get_notion_headers():
    with open('/home/clawd/secrets/notion/api_key', 'r') as f:
        api_key = f.read().strip()
    return {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Notion-Version": "2022-06-28"
    }

def load_state():
    if SOURCES_STATE.exists():
        return json.loads(SOURCES_STATE.read_text())
    return {"approved": [], "pending": [], "last_sync": None}

def save_state(state):
    SOURCES_STATE.write_text(json.dumps(state, indent=2))

def fetch_notion_sources(status_filter=None):
    """Fetch sources from Notion DB"""
    headers = get_notion_headers()
    
    filter_obj = {}
    if status_filter:
        filter_obj = {"property": "Status", "select": {"equals": status_filter}}
    
    body = {"page_size": 100}
    if filter_obj:
        body["filter"] = filter_obj
    
    resp = requests.post(
        f"https://api.notion.com/v1/databases/{NOTION_DB_ID}/query",
        headers=headers,
        json=body
    )
    
    if resp.status_code != 200:
        print(f"Error fetching from Notion: {resp.status_code}")
        return []
    
    sources = []
    for page in resp.json().get("results", []):
        props = page["properties"]
        
        name_arr = props.get("Name", {}).get("title", [])
        name = name_arr[0]["text"]["content"] if name_arr else ""
        
        url = props.get("URL", {}).get("url", "")
        
        tier_obj = props.get("Tier", {}).get("select")
        tier = tier_obj["name"] if tier_obj else "Low"
        
        dim_arr = props.get("Dimension", {}).get("multi_select", [])
        dimensions = [d["name"] for d in dim_arr]
        
        type_obj = props.get("Type", {}).get("select")
        source_type = type_obj["name"] if type_obj else "Other"
        
        status_obj = props.get("Status", {}).get("select")
        status = status_obj["name"] if status_obj else "Pending"
        
        notes_arr = props.get("Notes", {}).get("rich_text", [])
        notes = notes_arr[0]["text"]["content"] if notes_arr else ""
        
        sources.append({
            "id": page["id"],
            "name": name,
            "url": url,
            "tier": tier,
            "dimensions": dimensions,
            "type": source_type,
            "status": status,
            "notes": notes
        })
    
    return sources

def push_to_notion(source):
    """Push a pending source to Notion"""
    headers = get_notion_headers()
    
    data = {
        "parent": {"database_id": NOTION_DB_ID},
        "properties": {
            "Name": {"title": [{"text": {"content": source["name"]}}]},
            "URL": {"url": source["url"]},
            "Tier": {"select": {"name": source.get("tier", "Low")}},
            "Dimension": {"multi_select": [{"name": d} for d in source.get("dimensions", ["Design"])]},
            "Type": {"select": {"name": source.get("type", "Other")}},
            "Status": {"select": {"name": "Pending"}},
            "Added By": {"select": {"name": "Site Form"}},
            "Notes": {"rich_text": [{"text": {"content": source.get("notes", "")}}]}
        }
    }
    
    resp = requests.post("https://api.notion.com/v1/pages", headers=headers, json=data)
    return resp.status_code == 200

def notion_to_site():
    """Pull approved sources from Notion and update state"""
    print("Fetching approved sources from Notion...")
    sources = fetch_notion_sources("Approved")
    
    state = load_state()
    state["approved"] = sources
    state["last_sync"] = str(os.popen("date -u +%Y-%m-%dT%H:%M:%SZ").read().strip())
    save_state(state)
    
    print(f"✓ Synced {len(sources)} approved sources to state.json")
    
    # Group by tier for summary
    by_tier = {"Trust": [], "Medium": [], "Low": []}
    for s in sources:
        by_tier.get(s["tier"], by_tier["Low"]).append(s["name"])
    
    for tier, names in by_tier.items():
        if names:
            print(f"  {tier}: {', '.join(names)}")

def site_to_notion():
    """Push pending site submissions to Notion"""
    state = load_state()
    pending = state.get("pending", [])
    
    if not pending:
        print("No pending submissions to sync")
        return
    
    print(f"Pushing {len(pending)} pending sources to Notion...")
    
    synced = []
    failed = []
    
    for source in pending:
        if push_to_notion(source):
            synced.append(source["name"])
            print(f"  ✓ {source['name']}")
        else:
            failed.append(source["name"])
            print(f"  ✗ {source['name']}")
    
    # Clear synced from pending
    state["pending"] = [s for s in pending if s["name"] in failed]
    save_state(state)
    
    print(f"\nSynced: {len(synced)}, Failed: {len(failed)}")

def show_status():
    """Show current sync status"""
    state = load_state()
    notion_sources = fetch_notion_sources()
    
    approved = [s for s in notion_sources if s["status"] == "Approved"]
    pending = [s for s in notion_sources if s["status"] == "Pending"]
    local_pending = state.get("pending", [])
    
    print(f"=== Sources Sync Status ===")
    print(f"Notion approved: {len(approved)}")
    print(f"Notion pending review: {len(pending)}")
    print(f"Local pending upload: {len(local_pending)}")
    print(f"Last sync: {state.get('last_sync', 'never')}")
    
    if pending:
        print(f"\n⚠️  Pending review in Notion:")
        for s in pending:
            print(f"  - {s['name']} ({s['url']})")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)
    
    cmd = sys.argv[1]
    
    if cmd == "notion-to-site":
        notion_to_site()
    elif cmd == "site-to-notion":
        site_to_notion()
    elif cmd == "status":
        show_status()
    else:
        print(f"Unknown command: {cmd}")
        print(__doc__)
        sys.exit(1)
