const { httpGet, httpPost } = require("./http");
const { ADMIN_API, DEFAULT_PORT } = require("./constants");
const { readMasterRuntime, colors, apiUrl } = require("./utils");
const { green, yellow, cyan, white, red } = colors;

function formatUptime(seconds) {
  const UNITS = [
    { label: "d", divisor: 86400 },
    { label: "h", divisor: 3600 },
    { label: "m", divisor: 60 },
    { label: "s", divisor: 1 }
  ];

  let remaining = Math.floor(seconds);
  const parts = [];

  for (const { label, divisor } of UNITS) {
    if (remaining >= divisor) {
      const value = Math.floor(remaining / divisor);
      remaining = remaining % divisor;
      parts.push(`${value}${label}`);
    }
  }

  return parts.length > 0 ? parts.join(" ") : "0s";
}

async function resolveMasterPort(opts) {
  // 用户明确指定了端口，直接使用
  if (opts.port != null) {
    return opts.port;
  }
  // 从 runtime 文件读取 master 实际端口
  const runtime = await readMasterRuntime();
  if (runtime) {
    return runtime.managementPort;
  }
  // 兜底：默认端口
  return DEFAULT_PORT;
}

async function statusCommand(opts) {
  const masterPort = await resolveMasterPort(opts);
  const runtime = await readMasterRuntime();
  const displayPort = runtime ? runtime.publicPort : masterPort;

  console.log(`\n${yellow("●")} Master Status\n`);

  const health = await httpGet(apiUrl(masterPort, ADMIN_API.HEALTH));
  if (!health.ok || !health.body || typeof health.body.status !== "string") {
    console.error(`${red("✗")} Master service is not running`);
    process.exit(1);
  }

  const info = health.body;
  const statusIcon = info.status === "running" ? green("●") : cyan("●");

  console.log(`  ${green("Status")}      ${statusIcon} ${info.status}`);
  console.log(`  ${green("Version")}     ${white(info.version)}`);
  console.log(`  ${green("Uptime")}      ${white(formatUptime(info.uptime))}`);
  console.log(`  ${green("Projects")}    ${white(info.projects)}`);
  console.log("");

  const projects = await httpGet(apiUrl(masterPort, ADMIN_API.PROJECTS));
  if (projects.ok && projects.body) {
    const list = projects.body.projects;
    if (Array.isArray(list) && list.length > 0) {
      console.log(`  ${yellow("▸")} Registered Projects (${list.length}):`);
      console.log("  " + white("─".repeat(56)));
      for (const p of list) {
        console.log(`    ${green("hash")}     ${white(p.hash)}`);
        console.log(`    ${green("path")}     ${white(p.cwd)}`);
        // console.log(`    ${green('port')}     ${p.port}`);
        // if (p.subPort) console.log(`    ${green('subPort')}  ${p.subPort}`);
        console.log(`    ${green("url")}      ${cyan(`http://localhost:${displayPort}/${p.hash}/main/`)}`);
        console.log("  " + white("─".repeat(56)));
      }
    } else {
      console.log(`  ${white("─".repeat(58))}`);
      console.log(`      ${white("(No registered projects)")}`);
      console.log(`  ${white("─".repeat(58))}`);
    }
  }
  console.log("");
  process.exit(0);
}

async function stopCommand(hash, opts) {
  const masterPort = await resolveMasterPort(opts);

  if (opts.all) {
    const projects = await httpGet(apiUrl(masterPort, ADMIN_API.PROJECTS));
    if (!projects.ok || !projects.body) {
      console.error(`${red("✗")} Cannot connect to master service`);
      process.exit(1);
    }
    const list = projects.body.projects;
    if (!Array.isArray(list) || list.length === 0) {
      console.log(`${yellow("ℹ")} No running projects`);
      process.exit(0);
    }
    console.log(`\n${yellow("▸")} Stopping all ${list.length} projects...\n`);
    for (const p of list) {
      const res = await httpPost(apiUrl(masterPort, ADMIN_API.DEREGISTER), { hash: p.hash });
      if (res.ok) {
        console.log(`  ${green("✓")} Stopped: ${p.hash} (${p.cwd})`);
      } else {
        console.error(`  ${red("✗")} Failed to stop: ${p.hash} - ${res.error}`);
      }
    }
    console.log("");
    process.exit(0);
  }

  if (!hash) {
    console.error(`${red("✗")} Please specify project hash or use --all to stop all projects`);
    console.error(`   Usage: comphub stop <hash>`);
    console.error(`   Usage: comphub stop --all`);
    process.exit(1);
  }

  console.log(`\n${yellow("▸")} Stopping project ${hash}...`);
  const res = await httpPost(apiUrl(masterPort, ADMIN_API.DEREGISTER), { hash });
  if (res.ok) {
    console.log(`  ${green("✓")} Stopped: ${hash}\n`);
  } else {
    console.error(`  ${red("✗")} Failed to stop: ${res.error}\n`);
    process.exit(1);
  }
  process.exit(0);
}

async function killCommand(opts) {
  const masterPort = await resolveMasterPort(opts);
  console.log(`\n${yellow("▸")} Shutting down master process...\n`);

  const res = await httpPost(apiUrl(masterPort, ADMIN_API.SHUTDOWN), {});
  if (res.ok) {
    console.log(`${green("✓")} Master process has been shut down\n`);
  } else {
    console.error(`${red("✗")} Shutdown failed: ${res.error}\n`);
    process.exit(1);
  }
  process.exit(0);
}

async function fixCommand() {
  const fs = require("fs");
  const { MASTER_RUNTIME_FILE } = require("./constants");

  console.log(`\n${yellow("▸")} Checking master runtime...\n`);

  const runtime = await readMasterRuntime();
  if (runtime) {
    console.log(`  ${green("✓")} Master is running normally on port ${runtime.publicPort}\n`);
    process.exit(0);
  }

  if (fs.existsSync(MASTER_RUNTIME_FILE)) {
    try {
      fs.unlinkSync(MASTER_RUNTIME_FILE);
      console.log(`  ${green("✓")} Removed stale runtime file\n`);
    } catch {
      console.error(`  ${red("✗")} Failed to remove runtime file\n`);
      process.exit(1);
    }
  } else {
    console.log(`  ${yellow("ℹ")} No stale runtime file found\n`);
  }
  process.exit(0);
}

module.exports = { statusCommand, stopCommand, killCommand, fixCommand };
