"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const app = (0, express_1.default)();
app.use(express_1.default.json());
function readJson(filePath) {
    if (!fs_1.default.existsSync(filePath))
        return [];
    try {
        return JSON.parse(fs_1.default.readFileSync(filePath, 'utf-8'));
    }
    catch {
        return [];
    }
}
function writeJson(filePath, payload) {
    fs_1.default.mkdirSync(path_1.default.dirname(filePath), { recursive: true });
    fs_1.default.writeFileSync(filePath, JSON.stringify(payload, null, 2), 'utf-8');
}
const catalogDir = path_1.default.join(process.cwd(), '.catalog');
const teamsFile = path_1.default.join(catalogDir, 'teams.json');
const networksFile = path_1.default.join(catalogDir, 'skill-networks.json');
app.get('/api/v1/admin/teams', (_req, res) => {
    res.json({ ok: true, teams: readJson(teamsFile) });
});
app.get('/api/v1/admin/networks', (_req, res) => {
    res.json({ ok: true, networks: readJson(networksFile) });
});
app.post('/api/v1/admin/teams/upsert', (req, res) => {
    const body = req.body || {};
    if (!body.id)
        return res.status(400).json({ ok: false, error: 'id obrigatório' });
    const arr = readJson(teamsFile);
    const next = { id: String(body.id), domain: String(body.domain || 'general'), description: String(body.description || ''), slaProfile: String(body.slaProfile || 'balanced'), members: Array.isArray(body.members) ? body.members : [] };
    const idx = arr.findIndex((x) => x.id === next.id);
    if (idx >= 0)
        arr[idx] = { ...arr[idx], ...next };
    else
        arr.push(next);
    writeJson(teamsFile, arr);
    res.json({ ok: true, team: next });
});
app.post('/api/v1/admin/networks/upsert', (req, res) => {
    const body = req.body || {};
    if (!body.id)
        return res.status(400).json({ ok: false, error: 'id obrigatório' });
    const arr = readJson(networksFile);
    const next = { id: String(body.id), domain: String(body.domain || 'general'), nodes: Array.isArray(body.nodes) ? body.nodes : [] };
    const idx = arr.findIndex((x) => x.id === next.id);
    if (idx >= 0)
        arr[idx] = { ...arr[idx], ...next };
    else
        arr.push(next);
    writeJson(networksFile, arr);
    res.json({ ok: true, network: next });
});
app.get('/admin', (_req, res) => {
    res.sendFile(path_1.default.join(process.cwd(), 'src', 'admin_panel.html'));
});
const port = Number(process.env.ADMIN_PANEL_PORT || 8091);
app.listen(port, () => console.log(`[ADMIN_PANEL] running at http://localhost:${port}/admin`));
