"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.WorldClassCommands = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const SystemDoctor_1 = require("../orchestrator/SystemDoctor");
const GovernanceLayer_1 = require("../orchestrator/GovernanceLayer");
const GovernanceConsentStore_1 = require("../orchestrator/GovernanceConsentStore");
const SecurityEventStore_1 = require("../orchestrator/SecurityEventStore");
const AgentRegistry_1 = require("../orchestrator/AgentRegistry");
const SquadRegistry_1 = require("../orchestrator/SquadRegistry");
const SkillRegistryV2_1 = require("../orchestrator/SkillRegistryV2");
const child_process_1 = require("child_process");
class WorldClassCommands {
    root = process.cwd();
    doctorWorld() {
        const doctor = new SystemDoctor_1.SystemDoctor(this.root);
        return doctor.run().map(r => `${r.ok ? '✅' : '❌'} ${r.name}: ${r.detail}`);
    }
    doctorWorldDetailed() {
        const doctor = new SystemDoctor_1.SystemDoctor(this.root);
        const base = doctor.run();
        const oauthOnly = (process.env.OPENLIFE_RUNTIME_PROFILE || '').toLowerCase() === 'oauth-only';
        const classify = (name, ok) => {
            if (ok)
                return 'info';
            if (oauthOnly) {
                if (name === 'cli:ollama' || name === 'env:OPENAI_API_KEY' || name === 'env:GEMINI_API_KEY' || name === 'env:ANTHROPIC_API_KEY')
                    return 'info';
            }
            if (name.startsWith('runtime:') || name.includes('TELEGRAM_BOT_TOKEN') || name.startsWith('cli:'))
                return 'blocker';
            if (name.includes('promoted-assets') || name.includes('security-events'))
                return 'warning';
            return 'warning';
        };
        return base.map(r => ({ ...r, severity: classify(r.name, r.ok) }));
    }
    bootstrapWorld() {
        const bootstrapPath = path.join(this.root, '.openlife', 'world-bootstrap.json');
        fs.mkdirSync(path.dirname(bootstrapPath), { recursive: true });
        fs.writeFileSync(bootstrapPath, JSON.stringify({
            createdAt: new Date().toISOString(),
            bootstrap: 'world-class',
            checks: ['providers', 'cli', 'memory', 'governance', 'benchmark']
        }, null, 2), 'utf-8');
        return bootstrapPath;
    }
    memoryStatus() {
        return {
            hasMemoryRecords: fs.existsSync(path.join(this.root, '.artifacts', 'memory-records.json')),
            hasOperationalMemory: fs.existsSync(path.join(this.root, '.artifacts', 'operational-memory.json')),
            hasPromotedAssets: fs.existsSync(path.join(this.root, '.openlife', 'promoted-assets'))
        };
    }
    memoryProviderList() {
        return ['local', 'mempalace', 'mem0', 'zep-graphiti', 'redis-ams'];
    }
    memoryProviderUse(name) {
        const file = path.join(this.root, '.openlife', 'memory-provider.json');
        fs.mkdirSync(path.dirname(file), { recursive: true });
        fs.writeFileSync(file, JSON.stringify({ provider: name, updatedAt: new Date().toISOString() }, null, 2), 'utf-8');
        return file;
    }
    memoryTest(name) {
        return `Memory provider test preparado para: ${name}`;
    }
    swarmRun() {
        return 'Swarm run entrypoint preparado. Use o runtime multiagente/paralelo atual como base.';
    }
    swarmConsensusTest() {
        return 'Consensus test preparado. Próxima etapa: scorecard de branches e consenso formal.';
    }
    governanceStatus() {
        const security = new SecurityEventStore_1.SecurityEventStore(this.root);
        return {
            decision: new GovernanceLayer_1.GovernanceLayer().evaluate('status governance'),
            hasSecurityEvents: security.exists(),
            securityEventsPath: security.path()
        };
    }
    governanceAudit() {
        const security = new SecurityEventStore_1.SecurityEventStore(this.root);
        return `Governance audit baseline ativo. Security events: ${security.path()}`;
    }
    governanceRiskCheck(goal) {
        return new GovernanceLayer_1.GovernanceLayer().evaluate(goal);
    }
    governanceConsentApprove(userId, scope = 'destructive-action') {
        const consent = new GovernanceConsentStore_1.GovernanceConsentStore(this.root);
        consent.approve(userId, scope);
        return `Consentimento registrado para ${userId} no escopo ${scope}.`;
    }
    benchmarkRun() {
        const report = path.join(this.root, '.openlife', 'benchmark-run.json');
        fs.mkdirSync(path.dirname(report), { recursive: true });
        fs.writeFileSync(report, JSON.stringify({
            createdAt: new Date().toISOString(),
            benchmarks: ['openlife-internal-baseline', 'openclaw-comparison-pending', 'hermes-comparison-pending']
        }, null, 2), 'utf-8');
        return report;
    }
    benchmarkCompare() {
        return 'Benchmark compare preparado. Próxima etapa: benchmark reproduzível contra OpenClaw/Hermes.';
    }
    benchmarkReport() {
        return path.join(this.root, '.openlife', 'benchmark-run.json');
    }
    agentsListReal() {
        const agents = new AgentRegistry_1.AgentRegistry().all();
        return {
            type: 'agents-real-list',
            source: process.env.OPENLIFE_AGENT_ROOTS || path.join(this.root, '.catalog', 'agents'),
            total: agents.length,
            items: agents.map(a => ({ id: a.id, role: a.role, sourcePath: a.sourcePath, priority: a.priority }))
        };
    }
    squadsListReal() {
        const squads = new SquadRegistry_1.SquadRegistry().all();
        return {
            type: 'squads-real-list',
            source: process.env.OPENLIFE_SQUAD_ROOT || path.join(this.root, '.catalog', 'squads'),
            total: squads.length,
            items: squads.map(s => ({ id: s.id, domain: s.domain, sourcePath: s.sourcePath }))
        };
    }
    skillsListReal() {
        const skills = new SkillRegistryV2_1.SkillRegistryV2().all();
        return {
            type: 'skills-real-list',
            sources: [process.env.OPENLIFE_SKILL_ROOT || path.join(this.root, '.catalog', 'skills')],
            total: skills.length,
            items: skills.map(s => ({ id: s.id, sourcePath: s.sourcePath, capabilities: s.capabilities || [] }))
        };
    }
    orchestrationContract() {
        return {
            type: 'orchestration-contract',
            pipeline: ['planner', 'executor', 'reviewer', 'synthesizer'],
            io: {
                planner: { input: ['goal', 'history'], output: ['plan', 'successCriteria', 'normalizedGoal'] },
                executor: { input: ['plan', 'goal', 'skills', 'squads'], output: ['stdout|stderr', 'artifactPath', 'status', 'fallbackUsed?'] },
                reviewer: { input: ['goal', 'executorOutput', 'criteria'], output: ['approved', 'score', 'critique', 'nextAction'] },
                synthesizer: { input: ['state', 'executorOutput', 'review'], output: ['finalAnswer'] }
            },
            generatedAt: new Date().toISOString()
        };
    }
    writeOrchestrationSnapshot(extra = {}) {
        const file = path.join(this.root, '.openlife', 'orchestration-last-run.json');
        fs.mkdirSync(path.dirname(file), { recursive: true });
        fs.writeFileSync(file, JSON.stringify({
            type: 'orchestration-last-run',
            generatedAt: new Date().toISOString(),
            ...extra
        }, null, 2), 'utf-8');
        return file;
    }
    mcpStatusReal() {
        const check = (cmd) => {
            const r = (0, child_process_1.spawnSync)('bash', ['-lc', `command -v ${cmd}`], { encoding: 'utf-8' });
            return { available: r.status === 0, path: (r.stdout || '').trim() || null };
        };
        return {
            type: 'mcp-real-status',
            checks: {
                mcporter: check('mcporter'),
                claude: check('claude'),
                codex: check('codex')
            },
            timestamp: new Date().toISOString()
        };
    }
}
exports.WorldClassCommands = WorldClassCommands;
