/**
 * HLDP-ZY://native-repo/module/step-6
 * 光湖原生数据库 · 第6步 · HTTP API 服务
 *
 * @chain: D118 · 2026-05-31
 * @module: hldp-server
 * @step: 第6步 / 共8步
 * @deploy: BS-SG-002 · 端口 3912
 *
 * 三个端点:
 *   POST /hldp/write   — { path, content, intent, epoch }
 *   POST /hldp/read    — { path }
 *   POST /hldp/search  — { query }
 *
 * 铸渊通过 gatekeeper → localhost:3912 调用
 * 不需要单独的 Token —— 在 gatekeeper 层鉴权
 */

const http = require('http');
const { hldpWrite } = require('./step-3-hldp-write');
const { hldpRead, hldpTree, buildIndex } = require('./step-4-hldp-read-tree');
const { hldpSearch } = require('./step-5-hldp-search');

const PORT = parseInt(process.env.HLDP_PORT || '3912');
const HOST = process.env.HLDP_HOST || '127.0.0.1';

const server = http.createServer(async (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('X-HLDP-Version', '3.0');
  res.setHeader('X-Guardian', 'ICE-GL-ZY001');

  if (req.method !== 'POST') {
    res.writeHead(405);
    return res.end(JSON.stringify({ error: 'POST only' }));
  }

  let body = '';
  req.on('data', c => body += c);
  req.on('end', async () => {
    try {
      const input = JSON.parse(body);
      let result;

      if (req.url === '/hldp/write') {
        result = await hldpWrite({
          filePath: input.path,
          content: input.content,
          intent: input.intent,
          epoch: input.epoch
        });
      } else if (req.url === '/hldp/read') {
        result = await hldpRead(input.path);
      } else if (req.url === '/hldp/tree') {
        result = await hldpTree(input.path || '');
      } else if (req.url === '/hldp/search') {
        result = hldpSearch(input.query);
      } else if (req.url === '/hldp/index') {
        result = await buildIndex();
      } else if (req.url === '/hldp/health') {
        result = { ok: true, service: 'guanghu-native-repo', version: '0.1.0', uptime: process.uptime() };
      } else {
        res.writeHead(404);
        return res.end(JSON.stringify({ error: 'unknown endpoint' }));
      }

      res.writeHead(200);
      res.end(JSON.stringify(result));
    } catch (e) {
      res.writeHead(500);
      res.end(JSON.stringify({ ok: false, error: e.message }));
    }
  });
});

server.listen(PORT, HOST, () => {
  console.log('HLDP-NATIVE-REPO: ready on ' + HOST + ':' + PORT);
});
