const http = require("http");
const fs = require("fs");
const path = require("path");
const { URL } = require("url");
const { routeTask, formatTextReport } = require("./route-engine");
const { runDoctor, runStatus } = require("./doctor");

const MIME = {
  ".html": "text/html; charset=utf-8",
  ".js": "text/javascript; charset=utf-8",
  ".css": "text/css; charset=utf-8",
  ".json": "application/json; charset=utf-8",
  ".svg": "image/svg+xml"
};

function pkgUiDir() {
  return path.join(__dirname, "..", "..", "ui");
}

function readBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on("data", (c) => chunks.push(c));
    req.on("end", () => {
      try {
        const raw = Buffer.concat(chunks).toString("utf-8");
        resolve(raw ? JSON.parse(raw) : {});
      } catch (e) {
        reject(e);
      }
    });
    req.on("error", reject);
  });
}

function json(res, status, data) {
  const body = JSON.stringify(data);
  res.writeHead(status, {
    "Content-Type": "application/json; charset=utf-8",
    "Content-Length": Buffer.byteLength(body)
  });
  res.end(body);
}

function projectHealth(rootDir) {
  const doctor = runDoctor(rootDir);
  const status = runStatus(rootDir);
  return {
    ok: doctor.pass,
    doctor,
    status: {
      skills_on_disk: status.skills_on_disk,
      core_skills: status.core_skills,
      matrix_version: status.matrix_version,
      capint_package: status.capint_package
    }
  };
}

function buildChatCopy(result) {
  if (result.error) return result.error;
  const ei = result.execution_intent;
  const lines = [
    `Intent: ${ei.intent}`,
    `Capability: ${ei.capability}`,
    `Resolution: ${ei.resolution}`,
    `Resolution status: ${ei.resolution_status || "installed"}`,
    `Memory: ${ei.memory}`,
    `Plan: ${ei.plan}`
  ];
  if (ei.confirm?.enabled) {
    const opts = (ei.confirm_options || []).map((o) => o.id).join(" | ");
    lines.push(`Confirm: ${opts} (default: ${ei.confirm_default_option})`);
  }
  if (ei.explanation?.files_to_read?.length) {
    lines.push("Read first:");
    for (const f of ei.explanation.files_to_read) lines.push(`- ${f}`);
  }
  return lines.join("\n");
}

function createUiServer({ rootDir, uiDir = pkgUiDir(), port = 3721, host = "127.0.0.1" }) {
  const server = http.createServer(async (req, res) => {
    const url = new URL(req.url, `http://${host}:${port}`);
    const pathname = url.pathname;

    if (req.method === "GET" && pathname === "/api/health") {
      return json(res, 200, projectHealth(rootDir));
    }

    if (req.method === "POST" && pathname === "/api/route") {
      try {
        const body = await readBody(req);
        const task = String(body.task || "").trim();
        if (!task) return json(res, 400, { error: "task required" });
        const result = routeTask(task, rootDir);
        if (result.error) return json(res, 400, { error: result.error });
        return json(res, 200, {
          result,
          text_report: formatTextReport(result),
          chat_copy: buildChatCopy(result)
        });
      } catch (e) {
        return json(res, 400, { error: e.message });
      }
    }

    let filePath = pathname === "/" ? "/index.html" : pathname;
    filePath = path.normalize(filePath).replace(/^(\.\.[/\\])+/, "");
    const abs = path.join(uiDir, filePath);
    if (!abs.startsWith(path.resolve(uiDir))) {
      res.writeHead(403);
      return res.end("Forbidden");
    }
    if (!fs.existsSync(abs) || fs.statSync(abs).isDirectory()) {
      res.writeHead(404);
      return res.end("Not found");
    }
    const ext = path.extname(abs);
    const data = fs.readFileSync(abs);
    res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream" });
    res.end(data);
  });

  return {
    server,
    listen: () =>
      new Promise((resolve, reject) => {
        server.listen(port, host, () => resolve({ host, port, url: `http://${host}:${port}/` }));
        server.on("error", reject);
      }),
    close: () =>
      new Promise((resolve) => {
        server.close(() => resolve());
      })
  };
}

module.exports = { createUiServer, projectHealth, buildChatCopy, pkgUiDir };
