/*
 * Priority Forge — Linear cross-reference snapshot endpoint.
 *
 * There is no live Linear API; this serves the distilled snapshot at
 * data/linear-crossref.json, produced by `tsx scripts/build-linear-crossref.ts`
 * from the web-interact CDP scrapes. The Cross-Forge Topology view reads this
 * and computes the live pool↔Linear cross-reference client-side. Re-run the
 * generator after a fresh scrape to refresh; the `scrapedAt` field drives the
 * "stale" badge in the UI.
 */
import { Router, Request, Response } from 'express';
import fs from 'fs';
import path from 'path';

const router = Router();

// Mirror jsonStorage.resolveDataDir(): repo-local data/ unless overridden.
const DATA_DIR = process.env.PRIORITY_FORGE_DATA_DIR || path.join(__dirname, '../../data');
const CROSSREF_FILE = path.join(DATA_DIR, 'linear-crossref.json');

// GET /linear-crossref
router.get('/', (_req: Request, res: Response) => {
  try {
    if (!fs.existsSync(CROSSREF_FILE)) {
      res.json({
        generatedAt: null,
        scrapedAt: null,
        source: null,
        ticketCount: 0,
        tickets: {},
      });
      return;
    }
    res.json(JSON.parse(fs.readFileSync(CROSSREF_FILE, 'utf8')));
  } catch (err) {
    res.status(500).json({ error: err instanceof Error ? err.message : String(err) });
  }
});

export default router;
