// steamAssetsFetcher.js

import fs from "fs";
import path from "path";

// -----------------------------------------------------------------------
// Liste complète des chemins possibles pour les assets Steam
// -----------------------------------------------------------------------

const POSSIBLE_PATHS = [
    "logo.png",
    "logo_small.png",
    "logo_medium.png",
    "logo_large.png",

    "header.jpg",
    "header.png",

    "capsule.png",
    "capsule_231x87.jpg",
    "capsule_467x181.jpg",
    "capsule_184x69.jpg",
    "capsule_616x353.jpg",
    "capsule_467x181.png",

    "library_600x900.jpg",
    "library_hero.jpg",
    "library_hero_3840x2160.jpg",

    "capsule_1920x1080.jpg",
    "header_586x192.jpg",

    "page_bg_generated.jpg",
    "page_bg_generated_v6.jpg",
    "page_bg_generated_v6.png",

    "hero_capsule.jpg",
    "box.jpg",
    "box.png",
    "glyph.png",

    // Achievements & movies (génériques)
    "icon.png",
    "icon.jpg",
];

// -----------------------------------------------------------------------
// Fonction pour télécharger une URL
// -----------------------------------------------------------------------

async function downloadFile(url, dest) {

    try {
        const responce = await fetch (url);
        if (responce.status === 200) {
            const buffer = Buffer.from(await responce.arrayBuffer());
            fs.writeFileSync(dest, buffer);
            return true;
        }
    } catch (error) {
        console.error("Erreur de téléchargement :", error);
    }
   

    return false;
}

// -----------------------------------------------------------------------
// Programme principal
// -----------------------------------------------------------------------

async function main() {
    const appId = (process.argv[2]).trim();

    if (!appId) {
        console.error("Usage: node steamAssetsFetcher.js <AppID>");
        process.exit(1);
    }

    const baseUrl = `https://cdn.cloudflare.steamstatic.com/steam/apps/${appId}`;
    const outputDir = path.join("output", appId);
    fs.mkdirSync(outputDir, { recursive: true });

    console.log(`\nRecherche des assets pour AppID ${appId}\n`);

    let found = 0;
    let notFound = 0;

    for (const p of POSSIBLE_PATHS) {
        const url = `${baseUrl}/${p}`;
        const dest = path.join(outputDir, p.replace(/\//g, "_"));

        process.stdout.write(`Test: ${p} ... `);

        try {
            const ok = await downloadFile(url, dest);
            if (ok) {
                console.log("OK");
                found++;
            } else {
                console.log("Not found");
                notFound++;
            }
        } catch (err) {
            console.log("Error" ,err);
            notFound++;
        }
    }

    console.log("\nRésultat :");
    console.log(`  Trouvés : ${found}`);
    console.log(`  Absents : ${notFound}`);
    console.log(`\nFichiers stockés dans : ${outputDir}\n`);
}

main();
