// .gitea/scripts/downloadArtifactByName.js
// Purpose: Download and extract a single artifact by name from a given run.
// Env inputs:
//   GITEA_BASE_URL, OWNER, REPO, GITEA_PAT
//   RUN_ID            -> numeric/string
//   ARTIFACT_NAME     -> e.g. "frontend" or "webapi"
//   OUTPUT_DIR        -> e.g. "artifacts/frontend"

const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");

(async () => {
    const BASE = process.env.GITEA_BASE_URL;
    const OWNER = process.env.OWNER;
    const REPO  = process.env.REPO;
    const TOKEN = process.env.GITEA_PAT;
    const RUN_ID = process.env.RUN_ID;
    const NAME = process.env.ARTIFACT_NAME;
    const OUT_DIR = process.env.OUTPUT_DIR || path.join("artifacts", NAME || "");

    if (!BASE || !OWNER || !REPO) {
        console.error("Missing one of: GITEA_BASE_URL, OWNER, REPO");
        process.exit(1);
    }
    if (!TOKEN) {
        console.error("Missing GITEA_PAT");
        process.exit(1);
    }
    if (!RUN_ID || !NAME) {
        console.error("Missing RUN_ID or ARTIFACT_NAME");
        process.exit(1);
    }

    const url = `${BASE}/${OWNER}/${REPO}/actions/runs/${RUN_ID}/artifacts/${encodeURIComponent(NAME)}`;
    const zipPath = path.join(process.cwd(), `${NAME}.zip`);
    fs.mkdirSync(OUT_DIR, { recursive: true });

    console.log(`Downloading artifact "${NAME}" from run ${RUN_ID}`);
    console.log(`GET ${url}`);

    const res = await fetch(url, {
        method: "GET",
        redirect: "follow",
        headers: { Authorization: `token ${TOKEN}` }
    });

    if (!res.ok) {
        const text = await res.text().catch(() => "");
        console.error(`Download failed: ${res.status} ${res.statusText}\n${text}`);
        process.exit(1);
    }

    const buf = Buffer.from(await res.arrayBuffer());
    fs.writeFileSync(zipPath, buf);

    console.log(`Saved ZIP -> ${zipPath}`);
    console.log(`Extracting to -> ${OUT_DIR}`);

    execSync(`unzip -o "${zipPath}" -d "${OUT_DIR}"`, { stdio: "inherit" });
    fs.unlinkSync(zipPath);

    console.log("Done.");
})().catch(err => {
    console.error(err.stack || err.message || String(err));
    process.exit(1);
});