#!/usr/bin/env python3
"""Taste Board Ingest Pipeline

Takes candidate entries (from Julia's daily scan or manual adds),
captures screenshots, and adds them to the taste board data
with status: "pending" for human review.

Usage: python3 scripts/taste-ingest.py [candidates-file]
Default: products/taste-board/candidates/YYYY-MM-DD.json
"""

import json
import os
import sys
import subprocess
import uuid
from datetime import date, datetime
from pathlib import Path

WORKSPACE = Path("/root/.openclaw/workspace")
TASTE_DATA = WORKSPACE / "public/taste/prototype/data.json"
SCREENSHOTS_DIR = WORKSPACE / "public/taste/screenshots"
CANDIDATES_DIR = WORKSPACE / "products/taste-board/candidates"

def capture_screenshot(url, output_path, width=1280, height=800):
    """Capture screenshot using Playwright."""
    try:
        script = f"""
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
    browser = p.chromium.launch(headless=True, args=['--no-sandbox'])
    page = browser.new_page(viewport={{'width': {width}, 'height': {height}}})
    try:
        page.goto('{url}', wait_until='networkidle', timeout=20000)
    except:
        page.goto('{url}', wait_until='domcontentloaded', timeout=20000)
    page.wait_for_timeout(2000)
    page.screenshot(path='{output_path}', full_page=False)
    browser.close()
    print('OK')
"""
        result = subprocess.run(
            ['python3', '-c', script],
            capture_output=True, text=True, timeout=40
        )
        return 'OK' in result.stdout
    except Exception as e:
        print(f"  Screenshot failed for {url}: {e}", file=sys.stderr)
        return False

def compress_screenshot(path):
    """Compress to webp using available tools."""
    try:
        webp_path = str(path).rsplit('.', 1)[0] + '.webp'
        subprocess.run(
            ['convert', str(path), '-resize', '600x400>', '-quality', '55', webp_path],
            capture_output=True, timeout=15
        )
        if os.path.exists(webp_path):
            os.remove(str(path))
            return webp_path
    except:
        pass
    return str(path)

def main():
    # Determine candidates file
    if len(sys.argv) > 1:
        candidates_file = Path(sys.argv[1])
    else:
        today = date.today().isoformat()
        candidates_file = CANDIDATES_DIR / f"{today}.json"
    
    if not candidates_file.exists():
        print(f"No candidates file: {candidates_file}", file=sys.stderr)
        sys.exit(1)
    
    candidates = json.loads(candidates_file.read_text())
    print(f"📥 Processing {len(candidates)} candidates from {candidates_file.name}", file=sys.stderr)
    
    # Load existing taste board data
    existing = []
    if TASTE_DATA.exists():
        existing = json.loads(TASTE_DATA.read_text())
    
    existing_urls = {e.get('url', '').rstrip('/') for e in existing}
    
    SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)
    
    added = 0
    skipped = 0
    failed = 0
    
    for c in candidates:
        url = c.get('url', '').rstrip('/')
        if not url or url in existing_urls:
            skipped += 1
            continue
        
        # Generate entry ID
        entry_id = str(uuid.uuid4())[:8]
        screenshot_name = f"radar-{entry_id}.png"
        screenshot_path = SCREENSHOTS_DIR / screenshot_name
        
        print(f"  Capturing: {c.get('title', url)[:50]}...", file=sys.stderr)
        
        if capture_screenshot(url, str(screenshot_path)):
            # Compress
            final_path = compress_screenshot(screenshot_path)
            rel_path = os.path.relpath(final_path, WORKSPACE / "public/taste")
            
            entry = {
                "id": entry_id,
                "title": c.get("title", ""),
                "url": url,
                "screenshot": rel_path,
                "tags": c.get("tags", []),
                "type": "",
                "industry": "",
                "source": "trend-radar",
                "found_on": c.get("found_on", ""),
                "created": date.today().isoformat(),
                "qualification": {
                    "status": "pending",
                    "score": None,
                    "qualified_by": None
                },
                "extraction": None,  # Will be filled by Tatiana+Ogilvy
                "why_interesting": c.get("why_interesting", ""),
                "trend_link": c.get("trend_link"),
                "confidence": c.get("confidence", "signal")
            }
            
            existing.append(entry)
            existing_urls.add(url)
            added += 1
        else:
            failed += 1
    
    # Write updated taste board data
    TASTE_DATA.write_text(json.dumps(existing, indent=2))
    
    print(f"\n✅ Ingest complete: {added} added, {skipped} skipped, {failed} failed", file=sys.stderr)
    print(f"   Total entries in taste board: {len(existing)}", file=sys.stderr)
    
    # Output summary
    print(json.dumps({
        "added": added,
        "skipped": skipped, 
        "failed": failed,
        "total": len(existing)
    }))

if __name__ == "__main__":
    main()
