"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.personas = void 0;
const zod_1 = require("zod");
const connection_js_1 = require("./connection.js");
const PersonaRowSchema = zod_1.z.object({
    id: zod_1.z.string(),
    label: zod_1.z.string(),
    one_liner: zod_1.z.string(),
    system_prompt: zod_1.z.string(),
    recommended_lineage: zod_1.z.string().nullable(),
    builtin: zod_1.z.coerce.boolean(),
    forked_from: zod_1.z.string().nullable(),
    created_at: zod_1.z.number().int(),
    updated_at: zod_1.z.number().int(),
});
exports.personas = {
    async upsert(input) {
        const db = await (0, connection_js_1.getDb)();
        const now = Date.now();
        const existing = await exports.personas.getById(input.id);
        await db.execute({
            sql: `
        INSERT OR REPLACE INTO personas
          (id, label, one_liner, system_prompt, recommended_lineage, builtin, forked_from, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
      `,
            args: [
                input.id,
                input.label,
                input.one_liner,
                input.system_prompt,
                input.recommended_lineage ?? null,
                input.builtin ? 1 : 0,
                input.forked_from ?? null,
                existing?.created_at ?? now,
                now,
            ],
        });
        const row = await exports.personas.getById(input.id);
        if (!row)
            throw new Error(`personas.upsert: row vanished: ${input.id}`);
        return row;
    },
    async list() {
        const db = await (0, connection_js_1.getDb)();
        const result = await db.execute('SELECT * FROM personas ORDER BY label ASC');
        return result.rows.map((row) => PersonaRowSchema.parse(row));
    },
    async getById(id) {
        const db = await (0, connection_js_1.getDb)();
        const result = await db.execute({
            sql: 'SELECT * FROM personas WHERE id = ?',
            args: [id],
        });
        if (result.rows.length === 0)
            return null;
        return PersonaRowSchema.parse(result.rows[0]);
    },
    async delete(id) {
        const db = await (0, connection_js_1.getDb)();
        await db.execute({ sql: 'DELETE FROM personas WHERE id = ?', args: [id] });
    },
};
//# sourceMappingURL=personas.js.map