// bake-icons — resolve app icons from appstream and copy them into data/icons/
//
// Usage (from workspace root):
//   cargo run -p bake-icons
//   cargo run -p bake-icons -- data/apps.json data/icons
//
// Reads apps.json, uses the same appstream crate as the welcome app to find
// each app's icon, and copies it to <out-dir>/<app-id>.{png,svg}.
// Run this once on a Fedora machine with the relevant repos/flatpaks installed,
// then commit data/icons/ so the welcome app ships icons without needing
// a runtime appstream scan.

use serde::Deserialize;
use std::path::{Path, PathBuf};

#[derive(Deserialize)]
struct AppsJson {
    categories: Vec<Category>,
}

#[derive(Deserialize)]
struct Category {
    apps: Vec<App>,
}

#[derive(Deserialize)]
struct App {
    id: String,
    #[serde(rename = "type")]
    kind: String,
    #[serde(default)]
    package: String,
    #[serde(default)]
    icon: String,
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let json_path = args.get(1).map(|s| s.as_str()).unwrap_or("data/apps.json");
    let out_dir = args.get(2).map(|s| s.as_str()).unwrap_or("data/icons");

    std::fs::create_dir_all(out_dir).expect("create output icons dir");

    let content = std::fs::read_to_string(json_path)
        .unwrap_or_else(|e| panic!("cannot read {}: {}", json_path, e));
    let apps_json: AppsJson =
        serde_json::from_str(&content).expect("invalid apps.json");

    let mut found = 0usize;
    let mut cdn_only = 0usize;
    let mut missing = 0usize;

    for cat in &apps_json.categories {
        for app in &cat.apps {
            let (local_path, cdn_url) = rakuos_appstream::resolve_icon_for_package(
                &app.kind,
                &app.package,
                &app.icon,
            );

            if !local_path.is_empty() {
                let src = Path::new(&local_path);
                let ext = src
                    .extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("png");
                let dest = PathBuf::from(out_dir).join(format!("{}.{}", app.id, ext));
                match std::fs::copy(src, &dest) {
                    Ok(_) => {
                        println!("  ok  {}  ← {}", app.id, local_path);
                        found += 1;
                    }
                    Err(e) => {
                        eprintln!("  ERR {}  copy failed: {}", app.id, e);
                        missing += 1;
                    }
                }
            } else if !cdn_url.is_empty() {
                println!("  cdn {}  → {} (download manually if needed)", app.id, cdn_url);
                cdn_only += 1;
            } else {
                eprintln!("  ---  {}  no icon found (type={}, pkg={})", app.id, app.kind, app.package);
                missing += 1;
            }
        }
    }

    println!(
        "\nDone: {} copied, {} cdn-only (not downloaded), {} missing",
        found, cdn_only, missing
    );
    if cdn_only > 0 {
        println!("Tip: cdn-only icons can be downloaded with curl and placed in {}/", out_dir);
    }
}
