"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.listDomains = listDomains;
exports.listEntries = listEntries;
exports.getEntry = getEntry;
exports.setField = setField;
exports.removeField = removeField;
exports.deleteEntry = deleteEntry;
const picocolors_1 = __importDefault(require("picocolors"));
const client_1 = require("../client");
const format_1 = require("../format");
const DOMAIN_COLUMNS = [
    { key: 'domain', label: 'Domain', width: 24 },
    { key: 'count', label: 'Entries', width: 8, align: 'right' },
    { key: 'latest', label: 'Latest', width: 12, format: format_1.formatTime },
];
const ENTRY_COLUMNS = [
    { key: 'key', label: 'Key', width: 24 },
    { key: '_fieldCount', label: 'Fields', width: 8, align: 'right' },
    { key: 'tags', label: 'Tags', width: 20, format: (v) => (v || []).join(', ') },
    { key: 'updated_at', label: 'Updated', width: 12, format: format_1.formatTime },
];
async function listDomains(opts) {
    const data = await (0, client_1.apiFetch)('/knowledge/domains');
    (0, format_1.output)(data, data.domains || [], DOMAIN_COLUMNS, opts, 'domain');
}
async function listEntries(domain, opts) {
    const params = new URLSearchParams({ domain });
    if (opts.search)
        params.set('search', opts.search);
    if (opts.limit)
        params.set('limit', opts.limit);
    const data = await (0, client_1.apiFetch)(`/knowledge/entries?${params}`);
    const entries = (data.entries || []).map((e) => ({
        ...e,
        _fieldCount: e.data ? Object.keys(e.data).length : 0,
    }));
    (0, format_1.output)(data, entries, ENTRY_COLUMNS, opts, 'key');
}
async function getEntry(domain, key, opts) {
    const params = new URLSearchParams({ domain, key });
    const data = await (0, client_1.apiFetch)(`/knowledge/entry?${params}`);
    if (opts.json) {
        console.log(JSON.stringify(data, null, 2));
        return;
    }
    if (data.found === false) {
        console.log(picocolors_1.default.yellow(`\n  Not found: ${domain}/${key}\n`));
        return;
    }
    console.log(`\n  ${picocolors_1.default.bold(`${domain}/${key}`)} ${picocolors_1.default.dim(data.id)}`);
    if (data.tags?.length)
        console.log(`  Tags: ${data.tags.join(', ')}`);
    console.log(`  Updated: ${(0, format_1.formatTime)(data.updated_at)}\n`);
    console.log(JSON.stringify(data.data, null, 2));
    console.log();
}
async function setField(domain, key, path, value, opts) {
    // Try to parse as JSON, fall back to string
    let parsed = value;
    try {
        parsed = JSON.parse(value);
    }
    catch { /* keep as string */ }
    const data = await (0, client_1.apiFetch)('/knowledge/field', {
        method: 'PUT',
        body: JSON.stringify({ domain, key, path, value: parsed }),
    });
    if (opts.json) {
        console.log(JSON.stringify(data, null, 2));
        return;
    }
    console.log(`\n  ${picocolors_1.default.green('✓')} Set ${picocolors_1.default.bold(`${domain}/${key}`)} → ${path}\n`);
}
async function removeField(domain, key, path) {
    const params = new URLSearchParams({ domain, key, path });
    await (0, client_1.apiFetch)(`/knowledge/field?${params}`, { method: 'DELETE' });
    console.log(`\n  ${picocolors_1.default.green('✓')} Removed ${path} from ${picocolors_1.default.bold(`${domain}/${key}`)}\n`);
}
async function deleteEntry(domain, key) {
    const params = new URLSearchParams({ domain, key });
    await (0, client_1.apiFetch)(`/knowledge/entry?${params}`, { method: 'DELETE' });
    console.log(`\n  ${picocolors_1.default.green('✓')} Deleted ${picocolors_1.default.bold(`${domain}/${key}`)}\n`);
}
