"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const router = (0, express_1.Router)();
function projectRoot() {
    const candidates = [
        path.join(__dirname, '..'),
        path.join(__dirname, '..', '..'),
    ];
    for (const dir of candidates) {
        if (fs.existsSync(path.join(dir, 'docs')))
            return dir;
    }
    return candidates[0];
}
function listDocs(dir, prefix = '') {
    if (!fs.existsSync(dir))
        return [];
    const results = [];
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
        if (entry.isDirectory()) {
            results.push(...listDocs(path.join(dir, entry.name), rel));
        }
        else if (entry.name.endsWith('.md')) {
            const content = fs.readFileSync(path.join(dir, entry.name), 'utf-8');
            const firstLine = content.split('\n').find(l => l.startsWith('# '));
            const title = firstLine ? firstLine.replace(/^#\s+/, '') : entry.name;
            results.push({ path: rel, title });
        }
    }
    return results;
}
function resolveDocPath(docPath) {
    const root = projectRoot();
    // README.md lives at project root, everything else under docs/
    if (docPath === 'README.md') {
        const fp = path.join(root, 'README.md');
        return fs.existsSync(fp) ? fp : null;
    }
    const fp = path.join(root, 'docs', docPath);
    return fs.existsSync(fp) ? fp : null;
}
router.get('/', (_req, res) => {
    const root = projectRoot();
    const docs = [];
    // README first
    const readmePath = path.join(root, 'README.md');
    if (fs.existsSync(readmePath)) {
        docs.push({ path: 'README.md', title: 'Long Tail' });
    }
    docs.push(...listDocs(path.join(root, 'docs')));
    res.json({ docs });
});
// Use query param for doc path to avoid Express wildcard issues
router.get('/read', (req, res) => {
    const docPath = req.query.path;
    if (!docPath || docPath.includes('..')) {
        res.status(400).json({ error: 'Invalid path' });
        return;
    }
    const filePath = resolveDocPath(docPath);
    if (!filePath) {
        res.status(404).json({ error: 'Document not found' });
        return;
    }
    const content = fs.readFileSync(filePath, 'utf-8');
    res.json({ path: docPath, content });
});
exports.default = router;
