"use strict";
// src/test_config_tui.ts
// Tests for ConfigTui persistence helpers — focused on file-level effects
// (the interactive surface is exercised separately via the TUI).
//
// What we verify:
// - saveApiKeysToEnv writes to .env, masks correctly via existing helper
// - saveTelegramConfig persists token + chat id
// - validateTelegramToken catches format errors before going to the network
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 fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const InstallModules_1 = require("./cli/InstallModules");
let failed = 0;
function check(label, condition, detail) {
    if (condition) {
        console.log(`✅ ${label}`);
    }
    else {
        console.error(`❌ ${label}${detail ? ` — ${detail}` : ''}`);
        failed++;
    }
}
// 1. saveApiKeysToEnv idempotent (writing same key twice does not duplicate)
{
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openlife-cfg-keys-'));
    try {
        (0, InstallModules_1.saveApiKeysToEnv)(root, { openai: 'sk-aaa' });
        (0, InstallModules_1.saveApiKeysToEnv)(root, { openai: 'sk-bbb' });
        const env = fs.readFileSync(path.join(root, '.env'), 'utf-8');
        const matches = env.match(/^OPENAI_API_KEY=/gm) || [];
        check('OPENAI_API_KEY appears exactly once after two saves', matches.length === 1, `count=${matches.length}`);
        check('OPENAI_API_KEY reflects latest value', env.includes('OPENAI_API_KEY=sk-bbb'));
    }
    finally {
        fs.rmSync(root, { recursive: true, force: true });
    }
}
// 2. saveApiKeysToEnv preserves unrelated lines
{
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openlife-cfg-keys-mix-'));
    try {
        fs.writeFileSync(path.join(root, '.env'), 'SOME_OTHER=preserve_me\nFOO=bar\n', 'utf-8');
        (0, InstallModules_1.saveApiKeysToEnv)(root, { gemini: 'gem-xyz' });
        const env = fs.readFileSync(path.join(root, '.env'), 'utf-8');
        check('preserved unrelated SOME_OTHER', env.includes('SOME_OTHER=preserve_me'));
        check('preserved unrelated FOO', env.includes('FOO=bar'));
        check('added new GEMINI_API_KEY', env.includes('GEMINI_API_KEY=gem-xyz'));
    }
    finally {
        fs.rmSync(root, { recursive: true, force: true });
    }
}
// 3. saveTelegramConfig sets token + chat id idempotently
{
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openlife-cfg-tg-'));
    try {
        (0, InstallModules_1.saveTelegramConfig)(root, '123456789:AAEEABCDEFGHIJKLMNOPQRSTUVWXYZ0123', '999');
        (0, InstallModules_1.saveTelegramConfig)(root, '999999999:ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ', '999');
        const env = fs.readFileSync(path.join(root, '.env'), 'utf-8');
        const tokenCount = (env.match(/^TELEGRAM_BOT_TOKEN=/gm) || []).length;
        check('TELEGRAM_BOT_TOKEN appears exactly once', tokenCount === 1, `count=${tokenCount}`);
        check('TELEGRAM_BOT_TOKEN updated to second value', env.includes('TELEGRAM_BOT_TOKEN=999999999:'));
    }
    finally {
        fs.rmSync(root, { recursive: true, force: true });
    }
}
// 4. validateTelegramToken rejects bad format without going to network
{
    const r1 = (0, InstallModules_1.validateTelegramToken)(undefined);
    check('validate rejects undefined token', r1.ok === false);
    const r2 = (0, InstallModules_1.validateTelegramToken)('not-a-token');
    check('validate rejects malformed token', r2.ok === false && r2.detail.includes('inválido'));
    const r3 = (0, InstallModules_1.validateTelegramToken)('123:short');
    check('validate rejects token with short secret', r3.ok === false);
}
if (failed > 0) {
    console.error(`\n${failed} check(s) failed.`);
    process.exit(1);
}
console.log('\nTEST_CONFIG_TUI_OK');
