"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.TestHarness = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const Brain_1 = require("./Brain");
const Gatekeeper_1 = require("./Gatekeeper");
const IntentClassifier_1 = require("./IntentClassifier");
const VoiceManager_1 = require("./VoiceManager");
const ModelManager_1 = require("./ModelManager");
const Gateway_1 = require("./Gateway");
const RuntimeProbe_1 = require("./RuntimeProbe");
const RuntimePolicy_1 = require("./RuntimePolicy");
class TestHarness {
    brain = new Brain_1.Brain();
    gatekeeper = new Gatekeeper_1.Gatekeeper();
    voiceManager = new VoiceManager_1.VoiceManager();
    modelManager = new ModelManager_1.ModelManager();
    gateway = new Gateway_1.Gateway();
    runtimeProbe = new RuntimeProbe_1.RuntimeProbe();
    runtimePolicy = new RuntimePolicy_1.RuntimePolicy();
    async runPhase1Checks() {
        const results = [];
        results.push(await this.checkModelConfig());
        results.push(await this.checkRuntimeExecutors());
        results.push(await this.checkRuntimePolicyChain());
        results.push(await this.checkBrainPrimary());
        results.push(await this.checkFastPathMemory());
        results.push(await this.checkVoiceTts());
        results.push(await this.checkGatewayText());
        results.push(await this.checkGatewayImage());
        return results;
    }
    async checkModelConfig() {
        const config = this.modelManager.getModelConfig();
        const deduped = [config.primary, ...config.fallbacks].map(m => m.raw);
        const unique = new Set(deduped);
        if (deduped.length !== unique.size) {
            return { name: 'model-config', ok: false, detail: 'Há modelos duplicados na cadeia de fallback.' };
        }
        return {
            name: 'model-config',
            ok: true,
            detail: `Primário: ${config.primary.raw} | Fallbacks: ${config.fallbacks.map(f => f.raw).join(', ') || 'nenhum'}`
        };
    }
    async checkRuntimeExecutors() {
        try {
            const probes = await this.runtimeProbe.probeAll();
            const okCount = probes.filter((probe) => probe.available).length;
            return {
                name: 'runtime-executors',
                ok: okCount >= 1,
                detail: probes.map((probe) => `${probe.executor}:${probe.available ? 'ok' : 'fail'}:${probe.category}`).join(' | ')
            };
        }
        catch (error) {
            return { name: 'runtime-executors', ok: false, detail: error instanceof Error ? error.message : String(error) };
        }
    }
    async checkRuntimePolicyChain() {
        try {
            const research = this.runtimePolicy.decide('RESEARCH_ANALYSIS');
            const engineering = this.runtimePolicy.decide('ENGINEERING_BUILD');
            const ok = research.preferred.length > 0 && engineering.preferred.length > 0;
            return {
                name: 'runtime-policy-chain',
                ok,
                detail: `research=${research.preferred.join('>')} | engineering=${engineering.preferred.join('>')}`
            };
        }
        catch (error) {
            return { name: 'runtime-policy-chain', ok: false, detail: error instanceof Error ? error.message : String(error) };
        }
    }
    async checkBrainPrimary() {
        try {
            const response = await this.brain.think('Responda apenas com OK_BRAIN', 'OK_BRAIN');
            const ok = response.includes('OK_BRAIN');
            return {
                name: 'brain-primary',
                ok,
                detail: ok ? 'Brain respondeu via runtime principal.' : `Resposta inesperada: ${response}`
            };
        }
        catch (error) {
            return { name: 'brain-primary', ok: false, detail: error instanceof Error ? error.message : String(error) };
        }
    }
    async checkFastPathMemory() {
        try {
            const response = await this.gatekeeper.routeTask({ intent: IntentClassifier_1.TaskIntent.KNOWLEDGE_RETRIEVAL, budgetLimit: 0.1, requiresHarness: false }, 'Responda apenas OK_MEMORY', 'phase1-test-user');
            const ok = typeof response === 'string' && response.length > 0;
            return {
                name: 'fastpath-memory',
                ok,
                detail: ok ? `Gatekeeper respondeu (${response.slice(0, 120)})` : 'Gatekeeper não respondeu.'
            };
        }
        catch (error) {
            return { name: 'fastpath-memory', ok: false, detail: error instanceof Error ? error.message : String(error) };
        }
    }
    async checkVoiceTts() {
        try {
            const outputPath = await this.voiceManager.generateSpeech('Teste de voz do OpenLife.');
            const exists = fs.existsSync(outputPath);
            return {
                name: 'voice-tts',
                ok: exists,
                detail: exists ? `Áudio gerado em ${path.basename(outputPath)}` : 'Arquivo de áudio não foi criado.'
            };
        }
        catch (error) {
            return { name: 'voice-tts', ok: false, detail: error instanceof Error ? error.message : String(error) };
        }
    }
    async checkGatewayText() {
        try {
            const response = await this.gateway.processTextForTest('phase1-gateway-user', 'Responda apenas OK_GATEWAY');
            const ok = typeof response === 'string' && response.length > 0;
            return {
                name: 'gateway-text',
                ok,
                detail: ok ? `Gateway respondeu (${response.slice(0, 120)})` : 'Gateway não retornou resposta.'
            };
        }
        catch (error) {
            return { name: 'gateway-text', ok: false, detail: error instanceof Error ? error.message : String(error) };
        }
    }
    async checkGatewayImage() {
        try {
            const imagePath = path.join(process.cwd(), '.temp_images', 'AgACAgEAAxkBAAMcadbcsuXT9sQEbNGuKEEPX1fiMLEAAkgMaxtdRbhGvMTAvX1tmS8BAAMCAAN5AAM7BA.jpg');
            if (!fs.existsSync(imagePath)) {
                return { name: 'gateway-image', ok: true, detail: 'Imagem de teste ausente; check multimodal pulado explicitamente. Adicione fixture em .temp_images para validar visão completa.' };
            }
            const response = await this.gateway.processImageForTest('phase1-image-user', imagePath, 'Descreva esta imagem em uma frase.');
            const ok = typeof response === 'string' && response.length > 0 && !response.includes('CRITICAL ERROR');
            return {
                name: 'gateway-image',
                ok,
                detail: ok ? `Gateway imagem respondeu (${response.slice(0, 120)})` : `Resposta inválida: ${response}`
            };
        }
        catch (error) {
            return { name: 'gateway-image', ok: false, detail: error instanceof Error ? error.message : String(error) };
        }
    }
}
exports.TestHarness = TestHarness;
