"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const uuid_1 = require("uuid");
const config_1 = require("../config");
const agent_prompts_1 = require("../agent-prompts");
const router = (0, express_1.Router)();
// ── Global prompts (per user) ────────────────────────────────────────────────
// GET /api/prompts
router.get('/', (req, res) => {
    res.json((0, agent_prompts_1.readGlobalPrompts)(req.user?.username));
});
// POST /api/prompts
router.post('/', (req, res) => {
    const parsed = (0, agent_prompts_1.validatePromptInput)(req.body);
    if (typeof parsed === 'string') {
        res.status(400).json({ error: parsed });
        return;
    }
    const username = req.user?.username;
    const list = (0, agent_prompts_1.readGlobalPrompts)(username);
    const entry = {
        id: (0, uuid_1.v4)(),
        label: parsed.label,
        command: parsed.command,
        createdAt: new Date().toISOString(),
    };
    list.push(entry);
    (0, agent_prompts_1.writeGlobalPrompts)(list, username);
    res.status(201).json(entry);
});
// PUT /api/prompts/:id
router.put('/:id', (req, res) => {
    const { id } = req.params;
    const parsed = (0, agent_prompts_1.validatePromptInput)(req.body);
    if (typeof parsed === 'string') {
        res.status(400).json({ error: parsed });
        return;
    }
    const username = req.user?.username;
    const list = (0, agent_prompts_1.readGlobalPrompts)(username);
    const idx = list.findIndex((p) => p.id === id);
    if (idx < 0) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    list[idx] = { ...list[idx], label: parsed.label, command: parsed.command };
    (0, agent_prompts_1.writeGlobalPrompts)(list, username);
    res.json(list[idx]);
});
// DELETE /api/prompts/:id
router.delete('/:id', (req, res) => {
    const { id } = req.params;
    const username = req.user?.username;
    const list = (0, agent_prompts_1.readGlobalPrompts)(username);
    const filtered = list.filter((p) => p.id !== id);
    if (filtered.length === list.length) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    (0, agent_prompts_1.writeGlobalPrompts)(filtered, username);
    res.json({ success: true });
});
// ── Project prompts (stored in {folder}/.ccweb/agent-prompts.json) ──────────
/**
 * Resolve the project folder for a prompt operation, checking that the caller
 * has edit-level access (admin OR owner OR share with 'edit' permission).
 * Mirrors the permission model used by `routes/shortcuts.ts`.
 */
function resolveProject(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 { folderPath: project.folderPath, cliTool: project.cliTool };
}
// GET /api/prompts/project/:projectId
//   → { global: (AgentPrompt & {inserted})[], project: (AgentPrompt & {inserted})[] }
router.get('/project/:projectId', (req, res) => {
    const p = resolveProject(req.params.projectId, req.user?.username || '', res);
    if (!p)
        return;
    const claudeMd = (0, agent_prompts_1.readClaudeMd)(p.folderPath, p.cliTool);
    res.json({
        global: (0, agent_prompts_1.annotateInserted)((0, agent_prompts_1.readGlobalPrompts)(req.user?.username), claudeMd),
        project: (0, agent_prompts_1.annotateInserted)((0, agent_prompts_1.readProjectPrompts)(p.folderPath), claudeMd),
        instructionsFilename: (0, agent_prompts_1.instructionsFilename)(p.cliTool),
    });
});
// POST /api/prompts/project/:projectId
router.post('/project/:projectId', (req, res) => {
    const p = resolveProject(req.params.projectId, req.user?.username || '', res);
    if (!p)
        return;
    const parsed = (0, agent_prompts_1.validatePromptInput)(req.body);
    if (typeof parsed === 'string') {
        res.status(400).json({ error: parsed });
        return;
    }
    const list = (0, agent_prompts_1.readProjectPrompts)(p.folderPath);
    const entry = {
        id: (0, uuid_1.v4)(),
        label: parsed.label,
        command: parsed.command,
        createdAt: new Date().toISOString(),
    };
    list.push(entry);
    (0, agent_prompts_1.writeProjectPrompts)(p.folderPath, list);
    res.status(201).json(entry);
});
// PUT /api/prompts/project/:projectId/:id
router.put('/project/:projectId/:id', (req, res) => {
    const p = resolveProject(req.params.projectId, req.user?.username || '', res);
    if (!p)
        return;
    const { id } = req.params;
    const parsed = (0, agent_prompts_1.validatePromptInput)(req.body);
    if (typeof parsed === 'string') {
        res.status(400).json({ error: parsed });
        return;
    }
    const list = (0, agent_prompts_1.readProjectPrompts)(p.folderPath);
    const idx = list.findIndex((pr) => pr.id === id);
    if (idx < 0) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    list[idx] = { ...list[idx], label: parsed.label, command: parsed.command };
    (0, agent_prompts_1.writeProjectPrompts)(p.folderPath, list);
    res.json(list[idx]);
});
// DELETE /api/prompts/project/:projectId/:id
router.delete('/project/:projectId/:id', (req, res) => {
    const p = resolveProject(req.params.projectId, req.user?.username || '', res);
    if (!p)
        return;
    const { id } = req.params;
    const list = (0, agent_prompts_1.readProjectPrompts)(p.folderPath);
    const filtered = list.filter((pr) => pr.id !== id);
    if (filtered.length === list.length) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    (0, agent_prompts_1.writeProjectPrompts)(p.folderPath, filtered);
    res.json({ success: true });
});
// ── Instructions file toggle (insert / remove by exact text) ────────────────
// Underlying file is CLAUDE.md for claude, AGENTS.md for codex/gemini/etc.
// POST /api/prompts/project/:projectId/toggle
// body: { text: string, action: 'insert' | 'remove' }
router.post('/project/:projectId/toggle', (req, res) => {
    const p = resolveProject(req.params.projectId, req.user?.username || '', res);
    if (!p)
        return;
    const { text, action } = req.body;
    if (typeof text !== 'string' || !text.trim()) {
        res.status(400).json({ error: 'text is required' });
        return;
    }
    if (text.length > 8000) {
        res.status(400).json({ error: 'text must be ≤8000 characters' });
        return;
    }
    if (action === 'insert') {
        try {
            const result = (0, agent_prompts_1.insertIntoClaudeMd)(p.folderPath, text, p.cliTool);
            res.json({ action, ...result, inserted: true, instructionsFilename: (0, agent_prompts_1.instructionsFilename)(p.cliTool) });
        }
        catch (err) {
            res.status(500).json({ error: err.message });
        }
        return;
    }
    if (action === 'remove') {
        try {
            const result = (0, agent_prompts_1.removeFromClaudeMd)(p.folderPath, text, p.cliTool);
            if (result.changed) {
                res.json({ action, changed: true, inserted: false });
            }
            else {
                // 'not-found' means the exact text could not be located; distinct from
                // 'not-present' (file empty / text never there) so the frontend can
                // decide whether to surface a "please delete manually" toast.
                res.json({ action, changed: false, reason: result.reason, inserted: result.reason === 'not-found' });
            }
        }
        catch (err) {
            res.status(500).json({ error: err.message });
        }
        return;
    }
    res.status(400).json({ error: "action must be 'insert' or 'remove'" });
});
exports.default = router;
//# sourceMappingURL=agent-prompts.js.map