#!/usr/bin/env python3
"""
Taste Board Screenshot Pipeline
Uses Playwright CLI to capture screenshots for mymind entries.

Usage:
  python3 scripts/taste-screenshots.py [--tier 1|2|3] [--limit N] [--skip-existing]
"""

import json, os, sys, subprocess, argparse, time, hashlib
from pathlib import Path

TASTE_DIR = Path("/root/.openclaw/workspace/public/taste")
JSON_PATH = TASTE_DIR / "mymind-entries.json"
IMG_DIR = TASTE_DIR / "screenshots"
IMG_DIR.mkdir(exist_ok=True)

SKIP_DOMAINS = [
    "linkedin.com", "instagram.com", "open.spotify.com",
    "figma.com/community", "pinterest.com",
]

def get_tier(entry):
    tags_lower = ','.join(entry.get('tags', [])).lower()
    if 'wow' in tags_lower or 'inspiration' in tags_lower:
        return 1
    if 'spark' in tags_lower:
        return 2
    return 3

def should_skip(url):
    if not url:
        return True
    for d in SKIP_DOMAINS:
        if d in url:
            return True
    return False

def img_filename(entry):
    eid = entry.get('id', '')
    if eid:
        safe = eid.replace('/', '_').replace('\\', '_')[:50]
        return f"{safe}.jpg"
    url_hash = hashlib.md5(entry['url'].encode()).hexdigest()[:12]
    return f"{url_hash}.jpg"

def capture_screenshot(url, output_path, timeout=5000):
    """Capture screenshot using Playwright CLI."""
    try:
        result = subprocess.run(
            ['playwright', 'screenshot', '--wait-for-timeout', str(timeout), url, str(output_path)],
            capture_output=True, text=True, timeout=30
        )
        return result.returncode == 0
    except subprocess.TimeoutExpired:
        return False
    except Exception:
        return False

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--tier', type=int, default=1, choices=[1,2,3])
    parser.add_argument('--limit', type=int, default=10)
    parser.add_argument('--skip-existing', action='store_true', default=True)
    parser.add_argument('--no-skip', action='store_true', default=False)
    args = parser.parse_args()

    with open(JSON_PATH) as f:
        entries = json.load(f)

    skip_existing = not args.no_skip

    candidates = []
    already = 0
    for e in entries:
        if get_tier(e) <= args.tier and e.get('url') and not should_skip(e['url']):
            fname = img_filename(e)
            fpath = IMG_DIR / fname
            if skip_existing and fpath.exists() and fpath.stat().st_size > 5000:
                e['image'] = f"screenshots/{fname}"
                already += 1
                continue
            if e.get('type') == 'Image':
                continue
            candidates.append(e)

    print(f"Tier ≤{args.tier}: {len(candidates)} to capture, {already} already done (limit {args.limit})")

    captured = 0
    failed = 0
    for e in candidates[:args.limit]:
        fname = img_filename(e)
        fpath = IMG_DIR / fname
        title = e.get('title', '')[:40]
        
        print(f"  [{captured+failed+1}/{min(len(candidates), args.limit)}] {title}... ", end='', flush=True)
        
        ok = capture_screenshot(e['url'], fpath)
        if ok and fpath.exists() and fpath.stat().st_size > 5000:
            e['image'] = f"screenshots/{fname}"
            captured += 1
            print(f"✅ ({fpath.stat().st_size // 1024}KB)")
        else:
            if fpath.exists():
                fpath.unlink()
            failed += 1
            print("❌")
        
        time.sleep(0.5)

    # Save updated JSON
    with open(JSON_PATH, 'w') as f:
        json.dump(entries, f, indent=2, ensure_ascii=False)

    print(f"\nDone: {captured} captured, {failed} failed, {already} already existed")

if __name__ == '__main__':
    main()
