#!/usr/bin/env python3
"""
Fetch app icons from Flathub for apps in example_apps_config.json
"""

import json
import os
import re
import requests
from pathlib import Path

# Paths
SCRIPT_DIR = Path(__file__).parent
PROJECT_ROOT = SCRIPT_DIR.parent
CONFIG_PATH = PROJECT_ROOT / "data" / "example_apps_config.json"
ICONS_DIR = PROJECT_ROOT / "data" / "icons"


def get_flatpak_id(app_id: str) -> str | None:
    """Extract the flatpak ID from the app_id field.
    
    app_id format: app/org.example.AppName/x86_64/stable
    Returns: org.example.AppName
    """
    if not app_id:
        return None
    
    parts = app_id.split("/")
    if len(parts) >= 2:
        return parts[1]
    return None


def fetch_icon_url(flatpak_id: str) -> str | None:
    """Fetch the icon URL from Flathub app page."""
    url = f"https://flathub.org/apps/{flatpak_id}"
    
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        html = response.text
        
        # Find image URL ending with .png - stop at quotes, whitespace, or comma
        # Look for dl.flathub.org icon URLs
        pattern = rf'(https://dl\.flathub\.org/[^"\'\s,]+\.png)'
        matches = re.findall(pattern, html)
        
        if matches:
            # Prefer 128x128 icons, otherwise take the first
            for match in matches:
                if "128x128" in match and flatpak_id.replace(".", "/") in match:
                    return match
            # Fallback to first icon match
            for match in matches:
                if flatpak_id.split(".")[-1] in match or "icon" in match.lower():
                    return match
            return matches[0]
            
    except requests.RequestException as e:
        print(f"  Error fetching page for {flatpak_id}: {e}")
    
    return None


def download_icon(icon_url: str, app_name: str) -> bool:
    """Download icon to data/icons/{app_name}.png"""
    try:
        response = requests.get(icon_url, timeout=10)
        response.raise_for_status()
        
        icon_path = ICONS_DIR / f"{app_name}.png"
        icon_path.write_bytes(response.content)
        return True
        
    except requests.RequestException as e:
        print(f"  Error downloading icon: {e}")
    
    return False


def main():
    # Create icons directory if it doesn't exist
    ICONS_DIR.mkdir(parents=True, exist_ok=True)
    
    # Load config
    with open(CONFIG_PATH, "r") as f:
        config = json.load(f)
    
    # Process all categories
    categories = config.get("apps", {}).get("categories", [])
    
    total = 0
    success = 0
    skipped = 0
    
    for category in categories:
        apps = category.get("apps", [])
        
        for app in apps:
            name = app.get("name", "Unknown")
            app_id = app.get("app_id", "")
            package_manager = app.get("package_manager", "")
            
            # Skip non-flathub apps
            if package_manager != "flathub":
                continue
            
            # Skip apps without app_id
            if not app_id:
                print(f"⏭️  {name}: No app_id, skipping")
                skipped += 1
                continue
            
            total += 1
            
            # Check if icon already exists
            icon_path = ICONS_DIR / f"{name}.png"
            if icon_path.exists():
                print(f"✓  {name}: Icon already exists")
                success += 1
                continue
            
            # Get flatpak ID
            flatpak_id = get_flatpak_id(app_id)
            if not flatpak_id:
                print(f"⚠️  {name}: Could not extract flatpak ID from {app_id}")
                continue
            
            print(f"🔍 {name}: Fetching icon for {flatpak_id}...")
            
            # Fetch icon URL
            icon_url = fetch_icon_url(flatpak_id)
            if not icon_url:
                print(f"  ⚠️  Could not find icon URL")
                continue
            
            print(f"  📥 Downloading from {icon_url[:60]}...")
            
            # Download icon
            if download_icon(icon_url, name):
                print(f"  ✅ Saved to {icon_path}")
                success += 1
            else:
                print(f"  ❌ Failed to download")
    
    print(f"\n📊 Summary: {success}/{total} icons downloaded, {skipped} skipped (no app_id)")


if __name__ == "__main__":
    main()
