#!/usr/bin/env python3
"""
Auto-tag taste board candidates using vision analysis.
Analyzes images and applies tags like: color, type, illustration, photo, brand, etc.
"""

import json
import os
import base64
import subprocess
import sys

# Paths
STATE_FILE = '/home/clawd/workspace/public/taste/state.json'
TASTE_HTML = '/home/clawd/workspace/public/taste/index.html'
IMAGES_BASE = '/home/clawd/workspace/public'

# Valid tags (must match taste board filter buttons)
VALID_TAGS = [
    "color", "type", "illustration", "photo", "brand", 
    "3d", "motion", "website", "minimal", "bold", 
    "editorial", "food", "product", "texture", "geometric", "layout"
]

def get_candidates_from_html():
    """Parse CANDIDATES array from the taste board HTML."""
    import re
    with open(TASTE_HTML) as f:
        content = f.read()
    
    # Find CANDIDATES array
    match = re.search(r'const CANDIDATES = \[(.*?)\];', content, re.DOTALL)
    if not match:
        print("Could not find CANDIDATES in HTML")
        return []
    
    # Parse the array (it's JS, not JSON, so we need to be careful)
    candidates_str = match.group(1)
    
    # Extract individual objects using regex
    pattern = r"\{\s*id:\s*(\d+),\s*img:\s*'([^']+)',\s*title:\s*'([^']+)',"
    candidates = []
    for m in re.finditer(pattern, candidates_str):
        candidates.append({
            'id': int(m.group(1)),
            'img': m.group(2),
            'title': m.group(3)
        })
    
    return candidates

def analyze_image(image_path):
    """Use OpenClaw's image tool to analyze and tag an image."""
    # Build the prompt
    prompt = f'''Analyze this design image and categorize it. 
Return ONLY a JSON array of applicable tags from: {json.dumps(VALID_TAGS)}
Example: ["illustration", "color", "bold"]
Be selective - only include tags that clearly apply.'''
    
    # We can't call the image tool directly from Python,
    # so we'll output what needs to be analyzed
    return None  # Placeholder - will be filled by Kitt

def main():
    # Load current state
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE) as f:
            state = json.load(f)
    else:
        state = {"items": {}, "seenIds": []}
    
    # Get candidates
    candidates = get_candidates_from_html()
    print(f"Found {len(candidates)} candidates")
    
    # Count items needing tags
    need_tags = []
    for c in candidates:
        item_id = str(c['id'])
        item = state.get('items', {}).get(item_id, {})
        if item.get('status') == 'liked' and not item.get('tags'):
            need_tags.append(c)
    
    print(f"{len(need_tags)} curated items need tags")
    
    # Output candidates needing tags
    for c in need_tags[:20]:  # First 20
        img_path = c['img']
        if img_path.startswith('../'):
            img_path = os.path.join(IMAGES_BASE, img_path.replace('../', ''))
        print(f"ID {c['id']}: {c['title']}")
        print(f"  Image: {img_path}")
        if os.path.exists(img_path):
            print(f"  Status: EXISTS")
        else:
            print(f"  Status: MISSING")

if __name__ == '__main__':
    main()
