#!/usr/bin/env python3
"""Batch process Notion DB entries: set covers from URLs using Visual Capture pipeline."""

import argparse, json, os, sys, time, urllib.request, urllib.error

sys.path.insert(0, os.path.dirname(__file__))
from capture import microlink_capture, best_image, analyze_with_vision, set_notion_cover, get_notion_key

NOTION_DB = "2ff330c2-8646-81f0-bbd9-ec474393d7a5"


def query_notion_db(db_id, notion_key, limit=50):
    """Get entries with URL but no cover."""
    headers = {
        "Authorization": f"Bearer {notion_key}",
        "Content-Type": "application/json",
        "Notion-Version": "2022-06-28",
    }
    url = f"https://api.notion.com/v1/databases/{db_id}/query"
    pages = []
    body = {"page_size": min(limit, 100)}
    
    while len(pages) < limit:
        req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=30) as r:
            resp = json.loads(r.read())
        
        for page in resp.get("results", []):
            if page.get("cover"):
                continue
            # Find URL property
            page_url = None
            for prop_name, prop in page.get("properties", {}).items():
                if prop.get("type") == "url" and prop.get("url"):
                    page_url = prop["url"]
                    break
            if page_url:
                title = ""
                for prop_name, prop in page.get("properties", {}).items():
                    if prop.get("type") == "title":
                        title = "".join(t.get("plain_text", "") for t in prop.get("title", []))
                        break
                pages.append({"id": page["id"], "url": page_url, "title": title})
        
        if not resp.get("has_more") or len(pages) >= limit:
            break
        body["start_cursor"] = resp["next_cursor"]
    
    return pages[:limit]


def main():
    p = argparse.ArgumentParser(description="Batch Notion cover setter")
    p.add_argument("--limit", type=int, default=50)
    p.add_argument("--analyze", action="store_true")
    p.add_argument("--dry-run", action="store_true")
    p.add_argument("--db", default=NOTION_DB)
    args = p.parse_args()

    notion_key = get_notion_key()
    if not notion_key:
        print("No Notion API key found", file=sys.stderr)
        sys.exit(1)

    print(f"Querying Notion DB {args.db} for entries without covers...")
    pages = query_notion_db(args.db, notion_key, args.limit)
    print(f"Found {len(pages)} entries to process")

    for i, page in enumerate(pages):
        print(f"\n[{i+1}/{len(pages)}] {page['title'] or page['url']}")
        
        if args.dry_run:
            print(f"  Would capture: {page['url']}")
            continue

        try:
            cap = microlink_capture(page["url"])
            time.sleep(10)  # Rate limit Microlink (free tier)
            
            img = best_image(cap)
            if not img:
                print("  No image found, skipping")
                continue

            note = ""
            if args.analyze:
                analysis = analyze_with_vision(img)
                note = analysis.get("taste_note", "")
                print(f"  Taste note: {note}")

            ok = set_notion_cover(page["id"], img, note, notion_key)
            print(f"  Cover set: {ok} — {img[:80]}")
            time.sleep(0.35)  # Rate limit Notion

        except Exception as e:
            print(f"  Error: {e}", file=sys.stderr)


if __name__ == "__main__":
    main()
