"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 child_process_1 = require("child_process");
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const CLI = path.join(process.cwd(), 'dist', 'index.js');
const RUN_ID = `test-crud-${process.pid}-${Date.now()}`;
function rm(p) { try {
    fs.rmSync(p, { recursive: true, force: true });
}
catch { } }
function rmFromJson(filePath, idsKey, id) {
    try {
        if (!fs.existsSync(filePath))
            return;
        const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
        if (data && typeof data === 'object' && Array.isArray(data[idsKey])) {
            data[idsKey] = data[idsKey].filter((e) => e?.id !== id);
            fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
        }
        else if (Array.isArray(data)) {
            const filtered = data.filter((e) => e?.id !== id);
            fs.writeFileSync(filePath, JSON.stringify(filtered, null, 2));
        }
    }
    catch { }
}
const ROUND_TRIPS = [
    {
        label: 'agents',
        createArgs: ['agents', 'create', `${RUN_ID}-agent`, '--role', 'specialist', '--notes', 'crud-test'],
        listArgs: ['agents', 'list'],
        presentCheck: (out, id) => out.includes(id),
        cleanup: (id) => rm(path.join(process.cwd(), '.catalog', 'agents', id))
    },
    {
        label: 'squads',
        createArgs: ['squads', 'create', `${RUN_ID}-squad`, '--domain', 'general', '--notes', 'crud-test'],
        listArgs: ['squads', 'list'],
        presentCheck: (out, id) => out.includes(id),
        cleanup: (id) => rm(path.join(process.cwd(), '.catalog', 'squads', id))
    },
    {
        label: 'skills',
        createArgs: ['skills', 'create', `${RUN_ID}-skill`, '--notes', 'crud-test'],
        listArgs: ['skills', 'list'],
        presentCheck: (out, id) => out.includes(id),
        cleanup: (id) => rm(path.join(process.cwd(), '.catalog', 'skills', id))
    },
    {
        label: 'mcp',
        createArgs: ['mcp', 'create', `${RUN_ID}-mcp`, '--transport', 'stdio', '--entry', 'echo'],
        listArgs: ['mcp', 'status', '--real'],
        presentCheck: (out, id) => out.includes(id) || out.includes('"mcporter"'), // mcp list isn't a thing; mcp status shows registry indirectly
        cleanup: (id) => rm(path.join(process.cwd(), '.catalog', 'mcps', id))
    },
    {
        label: 'teams',
        createArgs: ['teams', 'upsert', `${RUN_ID}-team`, '--domain', 'general', '--description', 'crud-test', '--sla', 'balanced'],
        listArgs: ['teams', 'list'],
        presentCheck: (out, id) => out.includes(id),
        cleanup: (id) => rmFromJson(path.join(process.cwd(), '.catalog', 'teams.json'), 'teams', id)
    },
    {
        label: 'networks',
        createArgs: ['networks', 'upsert', `${RUN_ID}-net`, '--domain', 'general', '--capabilities', 'cap1,cap2'],
        listArgs: ['networks', 'list'],
        presentCheck: (out, id) => out.includes(id),
        cleanup: (id) => rmFromJson(path.join(process.cwd(), '.catalog', 'skill-networks.json'), 'networks', id)
    }
];
function runSync(args) {
    const r = (0, child_process_1.spawnSync)('node', [CLI, ...args], { encoding: 'utf-8', timeout: 15000 });
    return { code: r.status, stdout: r.stdout || '', stderr: r.stderr || '' };
}
async function main() {
    if (!fs.existsSync(CLI))
        throw new Error(`MISSING_BUILD: ${CLI}`);
    const failures = [];
    const cleanupIds = [];
    try {
        for (const rt of ROUND_TRIPS) {
            const id = rt.createArgs[rt.createArgs.indexOf(rt.label === 'teams' || rt.label === 'networks' ? 'upsert' : 'create') + 1];
            cleanupIds.push({ rt, id });
            // CREATE
            const c = runSync(rt.createArgs);
            if (c.code !== 0) {
                failures.push(`[${rt.label}] CREATE exit=${c.code} stderr=${(c.stderr || '').slice(0, 150)}`);
                continue;
            }
            // LIST + presence check
            const l = runSync(rt.listArgs);
            if (l.code !== 0 && l.code !== 1) {
                failures.push(`[${rt.label}] LIST exit=${l.code} stderr=${(l.stderr || '').slice(0, 150)}`);
                continue;
            }
            const combined = l.stdout + '\n' + l.stderr;
            if (!rt.presentCheck(combined, id)) {
                failures.push(`[${rt.label}] entity ${id} not visible in ${rt.listArgs.join(' ')} output`);
                continue;
            }
        }
    }
    finally {
        // Always cleanup
        for (const { rt, id } of cleanupIds) {
            try {
                rt.cleanup(id);
            }
            catch { }
        }
    }
    if (failures.length > 0) {
        throw new Error(`CRUD_ROUNDTRIP_FAILURES (${failures.length}):\n${failures.join('\n')}`);
    }
    console.log(`TEST_CLI_CRUD_ROUNDTRIP_OK (${ROUND_TRIPS.length} entity types, runId=${RUN_ID})`);
}
main().catch((err) => {
    console.error('TEST_CLI_CRUD_ROUNDTRIP_FAIL:', err?.message || err);
    process.exit(1);
});
