import { join } from "node:path";
import { existsSync, readFileSync } from "node:fs";
import type { PackageManagerInfo } from "@/types/index.js";

function readPackageManagerVersion(localPath: string, managerName: string): number | null {
  const packageJsonPath = join(localPath, "package.json");
  if (!existsSync(packageJsonPath)) return null;

  try {
    const pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as {
      packageManager?: unknown;
    };
    if (typeof pkg.packageManager !== "string") return null;

    const [name, version] = pkg.packageManager.split("@");
    if (name !== managerName || !version) return null;

    const major = Number.parseInt(version.split(".")[0] ?? "", 10);
    return Number.isNaN(major) ? null : major;
  } catch {
    return null;
  }
}

export function detectPackageManager(localPath: string, installCmd?: string[]): PackageManagerInfo {
  if (installCmd && installCmd.length >= 2) {
    return { cmd: installCmd[0]!, installArgs: installCmd.slice(1) };
  }

  const has = (name: string) => existsSync(join(localPath, name));

  if (has("bun.lockb") || has("bun.lock")) {
    return { cmd: "bun", installArgs: ["install", "--frozen-lockfile"] };
  }
  if (has("yarn.lock")) {
    const yarnMajor = readPackageManagerVersion(localPath, "yarn");
    const installArgs =
      yarnMajor !== null && yarnMajor >= 2
        ? ["install", "--immutable"]
        : ["install", "--frozen-lockfile"];
    return { cmd: "yarn", installArgs };
  }
  if (has("pnpm-lock.yaml")) {
    return { cmd: "pnpm", installArgs: ["install", "--frozen-lockfile"] };
  }
  if (has("package-lock.json")) {
    return { cmd: "npm", installArgs: ["install", "--ignore-engines"] };
  }
  return { cmd: "npm", installArgs: ["install", "--ignore-engines"] };
}
