"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 });
/*
 * INT-02 — Live integration test against Telegram Bot API.
 *
 * SIDE EFFECT: sends one real message to the allowlisted chat_id.
 * The message will appear in Rafael's Telegram chat with the bot.
 *
 * Requires TELEGRAM_BOT_TOKEN + OPENLIFE_TELEGRAM_ALLOWED_USER_ID in .env.
 *
 * NOT included in test:all. Run via: npm run test:integration-telegram
 */
const dotenv = __importStar(require("dotenv"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const telegraf_1 = require("telegraf");
dotenv.config();
const LOG_PATH = path.join(process.cwd(), 'docs', 'audit', 'integrations', 'telegram.log');
function logLine(line) {
    fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
    fs.appendFileSync(LOG_PATH, `${new Date().toISOString()} ${line}\n`);
}
async function main() {
    const token = process.env.TELEGRAM_BOT_TOKEN;
    const chatId = process.env.OPENLIFE_TELEGRAM_ALLOWED_USER_ID;
    if (!token || !chatId) {
        throw new Error(`MISSING_CREDS: token=${!!token} chatId=${!!chatId}`);
    }
    logLine(`START telegram live test (chat_id=${chatId})`);
    const bot = new telegraf_1.Telegraf(token);
    // Verify bot identity (read-only, no message sent)
    let botInfo;
    try {
        botInfo = await bot.telegram.getMe();
        logLine(`bot_info username=@${botInfo.username} id=${botInfo.id} is_bot=${botInfo.is_bot}`);
    }
    catch (err) {
        logLine(`FAIL getMe error=${err?.message || err}`);
        throw new Error(`TELEGRAM_GETME_FAILED: ${err?.message || err}`);
    }
    // Send real message
    const messageText = `🤖 AUDIT-OK from Phase 4 INT-02 — Total Feature Audit milestone — ${new Date().toISOString()}`;
    let sentMsg;
    const t0 = Date.now();
    try {
        sentMsg = await bot.telegram.sendMessage(chatId, messageText);
        const elapsed = Date.now() - t0;
        logLine(`OK message_id=${sentMsg.message_id} elapsed=${elapsed}ms`);
        console.log(`TEST_INTEGRATION_TELEGRAM_LIVE_OK (bot=@${botInfo.username}, message_id=${sentMsg.message_id}, elapsed=${elapsed}ms)`);
        console.log(`  log: ${LOG_PATH}`);
        console.log(`  message: ${messageText.slice(0, 80)}...`);
    }
    catch (err) {
        logLine(`FAIL sendMessage error=${err?.message || err}`);
        throw new Error(`TELEGRAM_SEND_FAILED: ${err?.message || err}`);
    }
    // Telegraf has no pending handle to close in this path (we never started polling),
    // so the process should exit cleanly. Add safety net just in case.
    setTimeout(() => process.exit(0), 100).unref();
}
main().catch((err) => {
    const msg = err?.message || String(err);
    try {
        logLine(`FAIL ${msg.slice(0, 300)}`);
    }
    catch { }
    console.error('TEST_INTEGRATION_TELEGRAM_LIVE_FAIL:', msg);
    process.exit(1);
});
