"use strict";
// backend/src/routes/information.ts
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 config_1 = require("../config");
const conversation_sync_1 = require("../information/conversation-sync");
const router = (0, express_1.Router)();
const MAX_RECENT_EXPANDS = 50;
function resolveProjectFolder(projectId, username, res) {
    const project = (0, config_1.getProject)(projectId);
    if (!project) {
        res.status(404).json({ error: 'Project not found' });
        return null;
    }
    if (!(0, config_1.isAdminUser)(username) && !(0, config_1.isProjectOwner)(project, username) &&
        !project.shares?.some((s) => s.username === username && s.permission === 'edit')) {
        res.status(403).json({ error: 'Access denied' });
        return null;
    }
    return project.folderPath;
}
// ── GET /api/information/:projectId/conversations ──
router.get('/:projectId/conversations', (req, res) => {
    const folder = resolveProjectFolder(req.params.projectId, req.user?.username || '', res);
    if (!folder)
        return;
    const ids = (0, conversation_sync_1.listConversationIds)(folder);
    const dir = (0, conversation_sync_1.infoDir)(folder);
    const conversations = [];
    for (const id of ids) {
        const meta = (0, conversation_sync_1.readMeta)(path.join(dir, id));
        if (!meta)
            continue;
        const latestVersion = meta.versions[meta.latest];
        conversations.push({
            id,
            started_at: meta.started_at,
            ended_at: meta.ended_at,
            summary: meta.summary,
            turns: meta.turns,
            latest: meta.latest,
            latest_tokens: latestVersion?.tokens ?? meta.original_tokens,
            original_tokens: meta.original_tokens,
            expand_count: meta.expand_stats.total_llm + meta.expand_stats.total_user,
        });
    }
    conversations.sort((a, b) => b.started_at.localeCompare(a.started_at));
    const limit = Math.min(parseInt(req.query.limit) || 50, 200);
    const offset = parseInt(req.query.offset) || 0;
    res.json(conversations.slice(offset, offset + limit));
});
// ── GET /api/information/:projectId/conversations/:convId ──
router.get('/:projectId/conversations/:convId', (req, res) => {
    const folder = resolveProjectFolder(req.params.projectId, req.user?.username || '', res);
    if (!folder)
        return;
    const convDir = path.join((0, conversation_sync_1.infoDir)(folder), req.params.convId);
    const meta = (0, conversation_sync_1.readMeta)(convDir);
    if (!meta) {
        res.status(404).json({ error: 'Conversation not found' });
        return;
    }
    let version = req.query.version || 'latest';
    if (version === 'latest')
        version = meta.latest;
    const versionEntry = meta.versions[version];
    if (!versionEntry) {
        res.status(404).json({ error: `Version ${version} not found` });
        return;
    }
    const filePath = path.join(convDir, versionEntry.file);
    let content;
    try {
        content = fs.readFileSync(filePath, 'utf-8');
    }
    catch {
        res.status(500).json({ error: 'Failed to read conversation file' });
        return;
    }
    // Filter to specific turns if requested
    const turnsParam = req.query.turns;
    if (turnsParam) {
        const requestedTurns = turnsParam.split(',').map(t => t.trim());
        const sections = content.split(/(?=^## )/m);
        content = sections.filter(section => {
            const match = section.match(/^## ([UA]\d+)/);
            return match && requestedTurns.includes(match[1]);
        }).join('\n');
    }
    // Record expand if requesting non-latest version
    const source = req.query.source === 'user' ? 'user' : 'llm';
    if (version !== meta.latest) {
        const record = { from: meta.latest, to: version, at: new Date().toISOString(), source };
        if (source === 'llm') {
            meta.expand_stats.total_llm += 1;
            if (turnsParam) {
                for (const turn of turnsParam.split(',').map(t => t.trim())) {
                    meta.expand_stats.by_turn[turn] = (meta.expand_stats.by_turn[turn] || 0) + 1;
                }
            }
        }
        else {
            meta.expand_stats.total_user += 1;
        }
        meta.expand_stats.recent.push(record);
        if (meta.expand_stats.recent.length > MAX_RECENT_EXPANDS) {
            meta.expand_stats.recent = meta.expand_stats.recent.slice(-MAX_RECENT_EXPANDS);
        }
        try {
            (0, conversation_sync_1.writeMeta)(convDir, meta);
        }
        catch { /* non-fatal */ }
    }
    res.json({
        conv_id: req.params.convId,
        version,
        tokens: versionEntry.tokens,
        content,
        available_versions: Object.keys(meta.versions),
        expand_stats: meta.expand_stats,
    });
});
exports.default = router;
//# sourceMappingURL=information.js.map