#!/usr/bin/env python3
"""Re-process Notion taste DB entries: set covers via Microlink API for pages with URLs but no covers."""

import requests, time, json, sys

NOTION_KEY = open("/home/clawd/secrets/notion/api_key").read().strip()
DB_ID = "2ff330c2-8646-81f0-bbd9-ec474393d7a5"
HEADERS = {"Authorization": f"Bearer {NOTION_KEY}", "Notion-Version": "2022-06-28", "Content-Type": "application/json"}
MICROLINK = "https://api.microlink.io/?url={}"
SKIP_PATTERNS = ["logo", "icon", "favicon"]

# 1. Query all pages
pages = []
cursor = None
while True:
    body = {"page_size": 100}
    if cursor:
        body["start_cursor"] = cursor
    r = requests.post(f"https://api.notion.com/v1/databases/{DB_ID}/query", headers=HEADERS, json=body)
    r.raise_for_status()
    data = r.json()
    pages.extend(data["results"])
    if not data.get("has_more"):
        break
    cursor = data["next_cursor"]
    time.sleep(0.35)

print(f"Total pages: {len(pages)}")

# 2. Filter: has Link URL, no cover
candidates = []
for p in pages:
    if p.get("cover"):
        continue
    props = p.get("properties", {})
    # Find URL property - try common names
    url = None
    for key, val in props.items():
        if val.get("type") == "url" and val.get("url"):
            url = val["url"]
            break
    if url:
        title = ""
        for key, val in props.items():
            if val.get("type") == "title":
                title = "".join(t.get("plain_text", "") for t in val.get("title", []))
                break
        candidates.append({"id": p["id"], "url": url, "title": title})

print(f"Candidates (URL, no cover): {len(candidates)}")

# 3. Process up to 50
limit = min(50, len(candidates))
set_count = skip_count = error_count = 0

for i, c in enumerate(candidates[:limit]):
    idx = f"[{i+1}/{limit}]"
    try:
        mr = requests.get(MICROLINK.format(c["url"]), timeout=15)
        md = mr.json()
        img_url = None
        if md.get("status") == "success" and md.get("data", {}).get("image", {}).get("url"):
            img_url = md["data"]["image"]["url"]
        
        if not img_url or not img_url.startswith("http"):
            print(f'{idx} Skip "{c["title"]}" — no image')
            skip_count += 1
            time.sleep(2)
            continue
        
        low = img_url.lower()
        if low.endswith(".svg") or any(p in low for p in SKIP_PATTERNS):
            print(f'{idx} Skip "{c["title"]}" — bad image: {img_url[:80]}')
            skip_count += 1
            time.sleep(2)
            continue

        # Set cover
        pr = requests.patch(f"https://api.notion.com/v1/pages/{c['id']}", headers=HEADERS,
                           json={"cover": {"type": "external", "external": {"url": img_url}}})
        pr.raise_for_status()
        print(f'{idx} Set cover for "{c["title"]}" → {img_url[:100]}')
        set_count += 1
        time.sleep(0.35)
    except Exception as e:
        print(f'{idx} Error "{c["title"]}": {e}')
        error_count += 1
    time.sleep(2)

print(f"\n=== Summary: {set_count} covers set, {skip_count} skipped, {error_count} errors ===")
