import https from "node:https";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const TOKEN = "36034f878a07e8705c577a838e5186b3d6010d03";
const OWNER = "Sucukdeluxe";
const REPO = "real-debrid-downloader";
const TAG = "v1.6.15";

const BODY = `## What's Changed in v1.6.15

### Bug Fixes

#### Session not transitioning to "Stop" when downloads finish (autoExtractWhenStopped)
- **Fixed: Session stayed in "running" state indefinitely after all downloads completed** when \`autoExtractWhenStopped\` was enabled
- Root cause: The scheduler's finalization check required \`packagePostProcessTasks.size === 0\` before calling \`finishRun()\`. With \`autoExtractWhenStopped\`, post-processing (extraction) tasks continue running after downloads finish, so the condition was never satisfied — the session never switched to "stop"
- **Fix:** When \`autoExtractWhenStopped\` is enabled, the scheduler now calls \`finishRun()\` as soon as all downloads are complete (no queued/active/delayed items), regardless of whether post-processing tasks are still running. Extraction continues in the background as idle extraction, exactly as intended by the setting. When \`autoExtractWhenStopped\` is disabled, the previous behavior is preserved (session waits for both downloads and extraction to complete)

#### Packages cannot be collapsed during extraction
- **Fixed: Clicking collapse on a package caused it to re-expand after 1-2 seconds** during extraction
- Same issue with the footer "Alle einklappen" button — packages would immediately re-expand
- Root cause: The auto-expand \`useEffect\` ran on every state update (\`emitState()\` call) and forcibly re-expanded any package with items in "Entpacken -" status. With the more frequent \`emitState()\` calls added in v1.6.13, this fired constantly, making it impossible for users to keep packages collapsed
- **Fix:** Added a \`useRef(Set)\` to track which packages have already been auto-expanded. Each package is now only auto-expanded **once** when extraction starts. If the user manually collapses it, it stays collapsed. The tracking is reset when the package is no longer extracting, so a future extraction cycle will auto-expand it again

### Files Changed
- \`src/main/download-manager.ts\` — Scheduler finalization condition now respects \`autoExtractWhenStopped\` setting
- \`src/renderer/App.tsx\` — Auto-expand useEffect now uses ref-based tracking for one-time expansion per extraction cycle
`;

function apiRequest(method, apiPath, body) {
  return new Promise((resolve, reject) => {
    const opts = {
      hostname: "codeberg.org",
      path: `/api/v1${apiPath}`,
      method,
      headers: { Authorization: `token ${TOKEN}`, "Content-Type": "application/json", Accept: "application/json" },
    };
    const req = https.request(opts, (res) => {
      const chunks = [];
      res.on("data", (c) => chunks.push(c));
      res.on("end", () => {
        const text = Buffer.concat(chunks).toString();
        if (res.statusCode >= 400) reject(new Error(`${res.statusCode} ${text}`));
        else resolve(JSON.parse(text || "{}"));
      });
    });
    req.on("error", reject);
    if (body) req.write(JSON.stringify(body));
    req.end();
  });
}

function uploadAsset(releaseId, filePath, fileName) {
  return new Promise((resolve, reject) => {
    const data = fs.readFileSync(filePath);
    const opts = {
      hostname: "codeberg.org",
      path: `/api/v1/repos/${OWNER}/${REPO}/releases/${releaseId}/assets?name=${encodeURIComponent(fileName)}`,
      method: "POST",
      headers: { Authorization: `token ${TOKEN}`, "Content-Type": "application/octet-stream", "Content-Length": data.length },
    };
    const req = https.request(opts, (res) => {
      const chunks = [];
      res.on("data", (c) => chunks.push(c));
      res.on("end", () => {
        const text = Buffer.concat(chunks).toString();
        if (res.statusCode >= 400) reject(new Error(`Upload ${fileName}: ${res.statusCode} ${text}`));
        else resolve(JSON.parse(text || "{}"));
      });
    });
    req.on("error", reject);
    req.write(data);
    req.end();
  });
}

async function main() {
  console.log("Creating release...");
  const release = await apiRequest("POST", `/repos/${OWNER}/${REPO}/releases`, {
    tag_name: TAG, name: TAG, body: BODY, draft: false, prerelease: false,
  });
  console.log(`Release created: ${release.id}`);
  const releaseDir = path.join(__dirname, "..", "release");
  const assets = [
    { file: "Real-Debrid-Downloader-Setup-1.6.15.exe", name: "Real-Debrid-Downloader-Setup-1.6.15.exe" },
    { file: "Real-Debrid-Downloader 1.6.15.exe", name: "Real-Debrid-Downloader-1.6.15.exe" },
    { file: "latest.yml", name: "latest.yml" },
    { file: "Real-Debrid-Downloader Setup 1.6.15.exe.blockmap", name: "Real-Debrid-Downloader-Setup-1.6.15.exe.blockmap" },
  ];
  for (const a of assets) {
    const p = path.join(releaseDir, a.file);
    if (!fs.existsSync(p)) { console.warn(`SKIP ${a.file}`); continue; }
    console.log(`Uploading ${a.name} ...`);
    await uploadAsset(release.id, p, a.name);
    console.log(`  done.`);
  }
  console.log("Release complete!");
}
main().catch((e) => { console.error(e); process.exit(1); });
