"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 });
exports.runPrecheck = runPrecheck;
exports.maskToken = maskToken;
exports.providedApiKeyEnvNames = providedApiKeyEnvNames;
exports.saveApiKeysToEnv = saveApiKeysToEnv;
exports.saveTelegramConfig = saveTelegramConfig;
exports.validateTelegramToken = validateTelegramToken;
exports.checkTelegram409Conflict = checkTelegram409Conflict;
exports.writeTelegramLock = writeTelegramLock;
exports.validateTelegramChatId = validateTelegramChatId;
exports.chatSmoke = chatSmoke;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const child_process_1 = require("child_process");
function runPrecheck() {
    const checks = [];
    try {
        const v = (0, child_process_1.execSync)('node -v', { encoding: 'utf-8' }).trim();
        checks.push({ name: 'node', ok: true, detail: v });
    }
    catch {
        checks.push({ name: 'node', ok: false, detail: 'node não encontrado' });
    }
    try {
        const v = (0, child_process_1.execSync)('npm -v', { encoding: 'utf-8' }).trim();
        checks.push({ name: 'npm', ok: true, detail: v });
    }
    catch {
        checks.push({ name: 'npm', ok: false, detail: 'npm não encontrado' });
    }
    const dirOk = fs.existsSync(process.cwd());
    checks.push({ name: 'workspace', ok: dirOk, detail: process.cwd() });
    return { ok: checks.every(c => c.ok), checks };
}
function maskToken(token) {
    if (!token)
        return '';
    if (token.length < 10)
        return '***';
    return `${token.slice(0, 6)}...${token.slice(-4)}`;
}
const API_KEY_ENV_MAP = {
    openai: 'OPENAI_API_KEY',
    anthropic: 'ANTHROPIC_API_KEY',
    gemini: 'GEMINI_API_KEY',
    openrouter: 'OPENROUTER_API_KEY',
    elevenlabs: 'ELEVENLABS_API_KEY',
};
function providedApiKeyEnvNames(keys) {
    return Object.keys(keys)
        .filter((k) => typeof keys[k] === 'string' && keys[k].trim().length > 0)
        .map((k) => API_KEY_ENV_MAP[k]);
}
function saveApiKeysToEnv(root, keys) {
    const envPath = path.join(root, '.env');
    const current = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8') : '';
    const provided = Object.keys(keys)
        .filter((k) => typeof keys[k] === 'string' && keys[k].trim().length > 0);
    if (provided.length === 0)
        return { saved: [], path: envPath };
    const envVars = new Set(provided.map((k) => API_KEY_ENV_MAP[k]));
    const lines = current
        .split('\n')
        .filter(Boolean)
        .filter((l) => {
        const eq = l.indexOf('=');
        if (eq < 0)
            return true;
        return !envVars.has(l.slice(0, eq));
    });
    for (const k of provided) {
        lines.push(`${API_KEY_ENV_MAP[k]}=${keys[k].trim()}`);
    }
    fs.writeFileSync(envPath, lines.join('\n') + '\n', 'utf-8');
    return { saved: provided.map((k) => API_KEY_ENV_MAP[k]), path: envPath };
}
function saveTelegramConfig(root, token, chatId) {
    const envPath = path.join(root, '.env');
    const current = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8') : '';
    const lines = current.split('\n').filter(Boolean).filter(l => !l.startsWith('TELEGRAM_BOT_TOKEN=') && !l.startsWith('TELEGRAM_CHAT_ID='));
    if (token)
        lines.push(`TELEGRAM_BOT_TOKEN=${token}`);
    if (chatId)
        lines.push(`TELEGRAM_CHAT_ID=${chatId}`);
    fs.writeFileSync(envPath, lines.join('\n') + '\n', 'utf-8');
    return { saved: true, path: envPath, maskedToken: token ? maskToken(token) : undefined };
}
function validateTelegramToken(token) {
    if (!token)
        return { ok: false, detail: 'token ausente' };
    const formatOk = /^\d{6,}:[A-Za-z0-9_-]{20,}$/.test(token);
    if (!formatOk)
        return { ok: false, detail: 'formato inválido' };
    try {
        const raw = (0, child_process_1.execFileSync)('curl', ['-sS', '--max-time', '12', `https://api.telegram.org/bot${token}/getMe`], { encoding: 'utf-8' }).trim();
        const parsed = JSON.parse(raw);
        if (parsed.ok)
            return { ok: true, detail: 'token válido (getMe OK)' };
        return { ok: false, detail: parsed.description || 'getMe retornou erro' };
    }
    catch (e) {
        const msg = e instanceof Error ? e.message : 'erro desconhecido';
        return { ok: false, detail: `falha na validação remota: ${msg}` };
    }
}
function checkTelegram409Conflict(root, token) {
    if (!token)
        return { ok: true, detail: 'token ausente, sem verificação de conflito' };
    const lockPath = path.join(root, '.openlife', 'telegram-poller.lock.json');
    if (!fs.existsSync(lockPath))
        return { ok: true, detail: 'sem lock ativo' };
    try {
        const lock = JSON.parse(fs.readFileSync(lockPath, 'utf-8'));
        if (lock.token && lock.token === token) {
            return { ok: false, detail: `conflito 409 provável: token já em uso (pid=${lock.pid ?? 'unknown'})` };
        }
        return { ok: true, detail: 'lock existe, mas com token diferente' };
    }
    catch {
        return { ok: true, detail: 'lock inválido, ignorado' };
    }
}
function writeTelegramLock(root, token) {
    if (!token)
        return;
    const lockPath = path.join(root, '.openlife', 'telegram-poller.lock.json');
    fs.mkdirSync(path.dirname(lockPath), { recursive: true });
    fs.writeFileSync(lockPath, JSON.stringify({ token, pid: process.pid, ts: new Date().toISOString() }, null, 2), 'utf-8');
}
function validateTelegramChatId(token, chatId) {
    if (!token)
        return { ok: false, detail: 'token ausente para validar chat_id' };
    if (!chatId)
        return { ok: true, detail: 'chat_id não informado (validação de envio pulada)' };
    const msg = encodeURIComponent('✅ OpenLife install test message');
    try {
        const cmd = `curl -sS --max-time 15 "https://api.telegram.org/bot${token}/sendMessage?chat_id=${chatId}&text=${msg}"`;
        const raw = (0, child_process_1.execSync)(cmd, { encoding: 'utf-8' }).trim();
        const parsed = JSON.parse(raw);
        if (parsed.ok)
            return { ok: true, detail: 'chat_id válido (sendMessage OK)' };
        return { ok: false, detail: parsed.description || 'sendMessage retornou erro' };
    }
    catch (e) {
        const msg = e instanceof Error ? e.message : 'erro desconhecido';
        return { ok: false, detail: `falha ao validar chat_id: ${msg}` };
    }
}
function chatSmoke(root = process.cwd()) {
    try {
        // Lazy require avoids pulling ChatTui into callers that only need Telegram/precheck helpers.
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const { runChatSmoke } = require('./ChatTui');
        const result = runChatSmoke({ cwd: root });
        return {
            ok: result.ok,
            detail: `${result.marker}: ${result.detail}; sessionId=${result.sessionId}; model=${result.model}; cwd=${result.cwd}`,
        };
    }
    catch (err) {
        return {
            ok: false,
            detail: `OPENLIFE_CHAT_SMOKE_FAIL: ${err instanceof Error ? err.message : String(err)}`,
        };
    }
}
