"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.AutonomousInstaller = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class AutonomousInstaller {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    install() {
        const filesCreated = [];
        const openlifeDir = path.join(this.root, '.openlife');
        fs.mkdirSync(openlifeDir, { recursive: true });
        const runtimeFile = path.join(openlifeDir, 'agent-runtime.json');
        if (!fs.existsSync(runtimeFile)) {
            fs.writeFileSync(runtimeFile, JSON.stringify({ running: false, mode: 'autonomous' }, null, 2), 'utf-8');
            filesCreated.push(runtimeFile);
        }
        const queueFile = path.join(openlifeDir, 'agent-queue.json');
        if (!fs.existsSync(queueFile)) {
            fs.writeFileSync(queueFile, JSON.stringify({ queuedObjectives: [], updatedAt: new Date().toISOString() }, null, 2), 'utf-8');
            filesCreated.push(queueFile);
        }
        const policyFile = path.join(openlifeDir, 'autonomous-policy.json');
        if (!fs.existsSync(policyFile)) {
            fs.writeFileSync(policyFile, JSON.stringify({
                maxConcurrentMissions: 1,
                requireGovernanceRiskCheck: true,
                autoPersistMemory: true,
                autoRunEvolution: true
            }, null, 2), 'utf-8');
            filesCreated.push(policyFile);
        }
        const systemdFile = path.join(this.root, 'scripts', 'openlife-agent.service.example');
        fs.mkdirSync(path.dirname(systemdFile), { recursive: true });
        fs.writeFileSync(systemdFile, this.systemdTemplate(), 'utf-8');
        filesCreated.push(systemdFile);
        const supervisorFile = path.join(this.root, 'scripts', 'openlife-agent.supervisord.conf.example');
        fs.writeFileSync(supervisorFile, this.supervisorTemplate(), 'utf-8');
        filesCreated.push(supervisorFile);
        const launcherFile = path.join(this.root, 'scripts', 'openlife-agent-start.sh');
        fs.writeFileSync(launcherFile, this.launcherTemplate(), 'utf-8');
        fs.chmodSync(launcherFile, 0o755);
        filesCreated.push(launcherFile);
        const installManifest = path.join(openlifeDir, 'autonomous-install-manifest.json');
        fs.writeFileSync(installManifest, JSON.stringify({
            installedAt: new Date().toISOString(),
            root: this.root,
            filesCreated
        }, null, 2), 'utf-8');
        filesCreated.push(installManifest);
        return {
            installedAt: new Date().toISOString(),
            root: this.root,
            filesCreated,
            nextCommands: [
                'openlife mode set autonomous --host claude-code',
                'openlife agent start',
                'openlife agent status'
            ]
        };
    }
    launcherTemplate() {
        return `#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
node dist/index.js mode set autonomous --host claude-code
node dist/index.js agent start
`;
    }
    systemdTemplate() {
        return `[Unit]
Description=OpenLife Autonomous Agent
After=network.target

[Service]
Type=simple
WorkingDirectory=${this.root}
ExecStart=/usr/bin/node ${this.root}/dist/index.js start --daemon
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
`;
    }
    supervisorTemplate() {
        return `[program:openlife-agent]
command=/usr/bin/node ${this.root}/dist/index.js start --daemon
directory=${this.root}
autostart=true
autorestart=true
startsecs=5
stderr_logfile=${this.root}/.openlife/logs/agent.err.log
stdout_logfile=${this.root}/.openlife/logs/agent.out.log
`;
    }
}
exports.AutonomousInstaller = AutonomousInstaller;
