const path = require("path");
const fs = require("fs");
const crypto = require("crypto");
const { MASTER_RUNTIME_FILE } = require("./constants");

const projectRoot = path.resolve(__dirname, "../..");

function readJson(p) {
  return JSON.parse(fs.readFileSync(p, "utf8"));
}

/**
 * 加载项目根目录的 .comphub.json 或 .comphub.js
 * 作为命令行参数的 fallback，优先级低于 CLI 选项
 */
function loadComphubConfig(cwd) {
  const jsonPath = path.join(cwd, ".comphub.json");
  const jsPath = path.join(cwd, ".comphub.js");

  try {
    if (fs.existsSync(jsonPath)) {
      return readJson(jsonPath);
    }
  } catch {
    /* corrupted json, try js */
  }

  try {
    if (fs.existsSync(jsPath)) {
      const mod = require(jsPath);
      return mod.default || mod;
    }
  } catch {
    /* ignore */
  }

  return {};
}

function getLocalPkgInfo() {
  const pkgPath = path.join(projectRoot, "package.json");
  const pkg = readJson(pkgPath);
  const entry = path.join(projectRoot, pkg.main || "dist/index.js");
  return { pkg, entry };
}

function computeHash(dir) {
  return crypto.createHash("sha256").update(dir).digest("hex").slice(0, 8);
}

async function readMasterRuntime() {
  try {
    if (fs.existsSync(MASTER_RUNTIME_FILE)) {
      const data = JSON.parse(fs.readFileSync(MASTER_RUNTIME_FILE, "utf8"));
      try {
        process.kill(data.pid, 0);
        // PID 存活不一定是 master 进程（PID 可能被复用），
        // 额外通过健康检查确认端口确实在服务
        const alive = await checkMasterAlive(data.managementPort);
        if (alive) return data;
      } catch {
        /* PID not found */
      }
      try {
        fs.unlinkSync(MASTER_RUNTIME_FILE);
      } catch {
        /* best effort */
      }
    }
  } catch {
    /* corrupted file */
  }
  return null;
}

function checkMasterAlive(port) {
  const { ADMIN_API } = require("./constants");
  const http = require("http");
  return new Promise(resolve => {
    const req = http.get(`http://localhost:${port}${ADMIN_API.HEALTH}`, res => {
      let body = "";
      res.on("data", chunk => (body += chunk));
      res.on("end", () => {
        try {
          const json = JSON.parse(body);
          resolve(typeof json.status === "string");
        } catch {
          resolve(false);
        }
      });
    });
    req.on("error", () => resolve(false));
    req.setTimeout(2000, () => {
      req.destroy();
      resolve(false);
    });
  });
}

const colors = {
  cyan: s => `\x1b[36m${s}\x1b[0m`,
  green: s => `\x1b[32m${s}\x1b[0m`,
  white: s => `\x1b[37m${s}\x1b[0m`,
  yellow: s => `\x1b[33m${s}\x1b[0m`,
  red: s => `\x1b[31m${s}\x1b[0m`
};

function apiUrl(port, pathname) {
  return `http://localhost:${port}${pathname}`;
}

module.exports = { getLocalPkgInfo, computeHash, projectRoot, readMasterRuntime, loadComphubConfig, colors, apiUrl };
