import { createHash } from "node:crypto";
import { mkdir, rm, stat } from "node:fs/promises";
import { join, relative } from "node:path";
import { createGzip } from "node:zlib";
import tar from "tar-stream";

import { buildDir, cleanup, codeGeneration, projectRoot, viteBuild } from "./build-common";

const releaseDir = join(projectRoot, "dist/release");
const binariesDir = join(releaseDir, "binaries");
const packagesDir = join(releaseDir, "packages");

export interface ReleaseTarget {
  arch: string;
  bunTarget: string;
  displayName: string;
  os: string;
}

export const ALL_TARGETS: ReleaseTarget[] = [
  { arch: "x64", bunTarget: "bun-linux-x64", displayName: "Linux x64 (glibc)", os: "linux" },
  { arch: "arm64", bunTarget: "bun-linux-arm64", displayName: "Linux ARM64 (glibc)", os: "linux" },
  { arch: "x64-musl", bunTarget: "bun-linux-x64-musl", displayName: "Linux x64 (musl)", os: "linux" },
  { arch: "arm64-musl", bunTarget: "bun-linux-arm64-musl", displayName: "Linux ARM64 (musl)", os: "linux" },
  { arch: "x64", bunTarget: "bun-windows-x64", displayName: "Windows x64", os: "windows" },
  { arch: "x64", bunTarget: "bun-darwin-x64", displayName: "macOS x64 (Intel)", os: "darwin" },
  { arch: "arm64", bunTarget: "bun-darwin-arm64", displayName: "macOS ARM64 (Apple Silicon)", os: "darwin" },
];

export function archiveName(target: ReleaseTarget, version: string): string {
  return `dial-server_${version}_${target.os}_${target.arch}.tar.gz`;
}

export function checksumName(target: ReleaseTarget, version: string): string {
  return `${archiveName(target, version)}.sha256`;
}

export async function compileTarget(target: ReleaseTarget, version: string): Promise<string> {
  const outfile = join(binariesDir, execName(target, version));
  console.log(`  编译 ${target.displayName}...`);

  const result = await Bun.build({
    compile: {
      autoloadBunfig: true,
      autoloadDotenv: true,
      outfile,
      target: target.bunTarget as Bun.Build.CompileTarget,
    },
    entrypoints: [join(buildDir, "server-entry.ts")],
    minify: true,
  });

  if (!result.success) {
    console.error(`  编译失败 (${target.displayName}):`, result.logs);
    process.exit(1);
  }

  return outfile;
}

export async function computeChecksum(archivePath: string): Promise<string> {
  const content = await Bun.file(archivePath).arrayBuffer();
  const hash = createHash("sha256").update(Buffer.from(content)).digest("hex");
  const filename = relative(packagesDir, archivePath);
  const checksumPath = `${archivePath}.sha256`;
  const checksumContent = `${hash}  ${filename}\n`;
  await Bun.write(checksumPath, checksumContent);
  return checksumPath;
}

export function execName(target: ReleaseTarget, version: string): string {
  const suffix = target.os === "windows" ? ".exe" : "";
  return `dial-server-${version}-${target.os}-${target.arch}${suffix}`;
}

export async function packageTarget(target: ReleaseTarget, version: string, binaryPath: string): Promise<string> {
  const archivePath = join(packagesDir, archiveName(target, version));
  const prefix = `dial-server_${version}_${target.os}_${target.arch}`;
  const binaryName = target.os === "windows" ? "dial-server.exe" : "dial-server";

  const binaryContent = await Bun.file(binaryPath).arrayBuffer();
  const probesContent = await Bun.file(join(projectRoot, "probes.example.yaml")).arrayBuffer();
  const licenseContent = await Bun.file(join(projectRoot, "LICENSE")).arrayBuffer();

  const pack = tar.pack();
  pack.entry(
    { mode: 0o755, name: `${prefix}/${binaryName}`, size: binaryContent.byteLength },
    Buffer.from(binaryContent),
  );
  pack.entry(
    { mode: 0o644, name: `${prefix}/probes.example.yaml`, size: probesContent.byteLength },
    Buffer.from(probesContent),
  );
  pack.entry({ mode: 0o644, name: `${prefix}/LICENSE`, size: licenseContent.byteLength }, Buffer.from(licenseContent));
  pack.finalize();

  const gzip = createGzip();
  const chunks: Buffer[] = [];

  await new Promise<void>((resolve, reject) => {
    pack.pipe(gzip);
    gzip.on("data", (chunk: Buffer) => chunks.push(chunk));
    gzip.on("end", resolve);
    gzip.on("error", reject);
  });

  await Bun.write(archivePath, Buffer.concat(chunks));
  return archivePath;
}

export function parseTargets(args: string[]): ReleaseTarget[] {
  const targetIndex = args.indexOf("--target");
  if (targetIndex === -1 || targetIndex === args.length - 1) {
    return ALL_TARGETS;
  }

  const targetValues = args[targetIndex + 1]!.split(",");
  const targets: ReleaseTarget[] = [];

  for (const value of targetValues) {
    const bunTarget = `bun-${value.trim()}`;
    const found = ALL_TARGETS.find((t) => t.bunTarget === bunTarget);
    if (!found) {
      const available = ALL_TARGETS.map((t) => t.bunTarget.replace(/^bun-/, "")).join(", ");
      console.error(`无效的 target: ${value.trim()}`);
      console.error(`可用的 target 值: ${available}`);
      process.exit(1);
    }
    targets.push(found);
  }

  return targets;
}

export async function printReport(binaries: string[], archives: string[]): Promise<void> {
  console.log("\n=== Release 报告 ===\n");

  console.log("裸二进制:");
  for (const binary of binaries) {
    const size = (await stat(binary)).size;
    const mb = (size / 1024 / 1024).toFixed(1);
    console.log(`  ${relative(projectRoot, binary)} (${mb} MB)`);
  }

  console.log("\n压缩包:");
  for (const archive of archives) {
    const size = (await stat(archive)).size;
    const mb = (size / 1024 / 1024).toFixed(1);
    console.log(`  ${relative(projectRoot, archive)} (${mb} MB)`);
  }
}

async function release() {
  const targets = parseTargets(process.argv);
  console.log(`Release 目标: ${targets.map((t) => t.displayName).join(", ")}\n`);

  try {
    await viteBuild();
    const version = await codeGeneration();

    console.log(`\n版本: ${version}`);
    console.log(`编译 ${targets.length} 个目标...\n`);

    await rm(releaseDir, { force: true, recursive: true });
    await mkdir(binariesDir, { recursive: true });
    await mkdir(packagesDir, { recursive: true });

    const binaries: string[] = [];
    for (const target of targets) {
      const binaryPath = await compileTarget(target, version);
      binaries.push(binaryPath);
    }

    const archives: string[] = [];
    for (let i = 0; i < targets.length; i++) {
      const target = targets[i]!;
      const binaryPath = binaries[i]!;
      console.log(`  打包 ${target.displayName}...`);
      const archivePath = await packageTarget(target, version, binaryPath);
      await computeChecksum(archivePath);
      archives.push(archivePath);
    }

    await cleanup();
    await printReport(binaries, archives);
    console.log("\nRelease 完成!");
  } catch (error) {
    await cleanup();
    console.error("Release 失败:", error);
    process.exit(1);
  }
}

if (import.meta.main) {
  await release();
}
