import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import fs from 'fs';
import path from 'path';

const CHANGELOG_PATH = process.env.CHANGELOG_PATH || '/opt/peercortex-app/CHANGELOG.md';

export async function changelogRoutes(fastify: FastifyInstance): Promise<void> {
  fastify.get(
    '/changelog-data',
    {
      // Override prefix — this is a top-level route, not under /api
      config: { noPrefix: true }
    },
    async (_request: FastifyRequest, reply: FastifyReply) => {
      reply.header('Access-Control-Allow-Origin', '*');
      reply.header('Cache-Control', 'public, max-age=3600');

      try {
        const md = fs.readFileSync(CHANGELOG_PATH, 'utf8');
        const entries: any[] = [];
        let current: any = null;
        let currentSection: any = null;

        for (const line of md.split('\n')) {
          const vMatch = line.match(/^## (?:v|\[)?([\d.]+)\]? — (.+)/);
          if (vMatch) {
            if (current) entries.push(current);
            current = { version: vMatch[1], date: vMatch[2].trim(), sections: [] };
            currentSection = null;
            continue;
          }
          const sMatch = line.match(/^### (.+)/);
          if (sMatch && current) {
            currentSection = { name: sMatch[1], items: [] };
            current.sections.push(currentSection);
            continue;
          }
          const iMatch = line.match(/^- (.+)/);
          if (iMatch && currentSection) {
            currentSection.items.push(iMatch[1]);
          }
        }
        if (current) entries.push(current);

        return reply.status(200).send(entries);
      } catch (e: any) {
        return reply.status(500).send({ error: e.message });
      }
    }
  );
}
