"use strict";

const fs = require("node:fs");
const http = require("node:http");
const path = require("node:path");

const DEFAULT_MAP = path.resolve(__dirname, "../../routing/persona-contribution-map.json");

function normalize(value) {
  return String(value || "").toLowerCase().replace(/[\s·._/-]+/g, " ").trim();
}

function recall(map, query) {
  const needle = normalize(query);
  const terms = needle.split(" ").filter(term => term.length >= 2);
  if (!needle) return [];
  return map.contributions.map(item => {
    const identifiers = [item.id, item.arrival_id, ...(item.project_ids || [])];
    const keywords = item.keywords || [];
    const haystack = normalize([...identifiers, item.arrival_name, item.title, ...keywords].join(" "));
    let score = identifiers.reduce((total, id) => total + (needle.includes(normalize(id)) ? 100 : 0), 0);
    score += keywords.reduce((total, keyword) => total + (needle.includes(normalize(keyword)) ? 20 : 0), 0);
    score += terms.reduce((total, term) => total + (haystack.includes(term) ? 5 : 0), 0);
    if (haystack.includes(needle)) score += 10;
    return { item, score };
  }).filter(row => row.score > 0)
    .sort((a, b) => b.score - a.score || a.item.id.localeCompare(b.item.id))
    .map(({ item, score }) => ({
      score,
      contribution_id: item.id,
      arrival: { id: item.arrival_id, name: item.arrival_name },
      title: item.title,
      paths: item.canonical_paths,
      grants_execution_authority: false,
    }));
}

function createServer(options = {}) {
  const mapFile = options.mapFile || process.env.GLS0231_MAP || DEFAULT_MAP;
  return http.createServer((req, res) => {
    const url = new URL(req.url, "http://localhost");
    if (req.method !== "GET") return json(res, 405, { error: "method_not_allowed" });
    if (url.pathname === "/health") return json(res, 200, { ok: true, service: "gls-0231-light-arrival-navigation", mode: "read-only" });
    if (url.pathname !== "/v1/recall") return json(res, 404, { error: "not_found" });
    let map;
    try { map = JSON.parse(fs.readFileSync(mapFile, "utf8")); }
    catch { return json(res, 503, { error: "contribution_map_unavailable" }); }
    const query = String(url.searchParams.get("q") || "").slice(0, 200);
    const matches = recall(map, query);
    return json(res, 200, {
      schema: "guanghu.route-recall-response/v1",
      status: matches.length ? "FOUND_CONFIDENT_PATH" : "NO_TRUSTED_PATH",
      query,
      matches,
      grants_execution_authority: false,
    });
  });
}

function json(res, status, value) {
  res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff" });
  res.end(JSON.stringify(value));
}

if (require.main === module) {
  const host = process.env.GLS0231_HOST || "127.0.0.1";
  const port = Number(process.env.GLS0231_PORT || 3924);
  createServer().listen(port, host, () => process.stdout.write(`gls-0231 navigation listening on ${host}:${port}\n`));
}

module.exports = { createServer, recall };
