#!/usr/bin/env node
// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only
/**
 * @file lumenflow-enable.ts
 * Restore LumenFlow enforcement after `lumenflow:disable` (WU-2590).
 *
 * Reads `.lumenflow/state/enforcement-prior.json` written by `lumenflow:disable`
 * and restores the prior flag values. If no prior state exists, defaults to all
 * flags true (safe default for a fresh enable).
 *
 * Usage:
 *   pnpm lumenflow:enable
 *   pnpm lumenflow:enable --client claude-code
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
// eslint-disable-next-line security/detect-child-process -- legitimate CLI subprocess
import { spawnSync } from 'node:child_process';
import { createWUParser, LUMENFLOW_CLIENT_IDS } from '@lumenflow/core';
import { runCLI } from './cli-entry-point.js';
import { integrateClaudeCode } from './commands/integrate.js';
const LOG_PREFIX = '[lumenflow:enable]';
const PRIOR_STATE_REL_PATH = path.join('.lumenflow', 'state', 'enforcement-prior.json');
const DEFAULT_ENFORCEMENT = {
    hooks: true,
    block_outside_worktree: true,
    require_wu_for_edits: true,
    warn_on_stop_without_wu_done: true,
};
export function parseEnableOptions() {
    const opts = createWUParser({
        name: 'lumenflow-enable',
        description: 'Re-enable LumenFlow enforcement previously disabled via lumenflow:disable.',
        options: [
            {
                name: 'client',
                flags: '--client <type>',
                description: 'Scope to a single client (default: claude-code)',
            },
            {
                name: 'json',
                flags: '--json',
                description: 'Emit machine-readable JSON output',
                type: 'boolean',
            },
        ],
    });
    return {
        client: opts.client ?? LUMENFLOW_CLIENT_IDS.CLAUDE_CODE,
        json: opts.json ?? false,
    };
}
export function readPriorState(projectDir, client) {
    const priorPath = path.join(projectDir, PRIOR_STATE_REL_PATH);
    if (!fs.existsSync(priorPath))
        return null;
    try {
        const parsed = JSON.parse(fs.readFileSync(priorPath, 'utf-8'));
        return parsed[client] ?? null;
    }
    catch {
        return null;
    }
}
export function clearPriorState(projectDir, client) {
    const priorPath = path.join(projectDir, PRIOR_STATE_REL_PATH);
    if (!fs.existsSync(priorPath))
        return;
    try {
        const parsed = JSON.parse(fs.readFileSync(priorPath, 'utf-8'));
        delete parsed[client];
        if (Object.keys(parsed).length === 0) {
            fs.unlinkSync(priorPath);
        }
        else {
            fs.writeFileSync(priorPath, JSON.stringify(parsed, null, 2) + '\n', 'utf-8');
        }
    }
    catch {
        // ignore — not critical
    }
}
export async function enableForClient(projectDir, client, runConfigSet) {
    const prior = readPriorState(projectDir, client);
    const enforcement = prior ?? DEFAULT_ENFORCEMENT;
    const restoredFrom = prior ? 'prior-state' : 'defaults';
    // Write each flag via config:set
    for (const flag of Object.keys(DEFAULT_ENFORCEMENT)) {
        const value = enforcement[flag] ?? DEFAULT_ENFORCEMENT[flag] ?? false;
        if (runConfigSet) {
            runConfigSet(projectDir, [
                `software_delivery.agents.clients.${client}.enforcement.${flag}`,
                String(value),
            ]);
        }
        else {
            const binPath = path.join(projectDir, 'packages', '@lumenflow', 'cli', 'dist', 'config-set.js');
            const res = spawnSync(process.execPath, [
                binPath,
                '--key',
                `software_delivery.agents.clients.${client}.enforcement.${flag}`,
                '--value',
                String(value),
            ], { cwd: projectDir, stdio: 'inherit' });
            if (res.status !== 0)
                throw new Error(`config:set failed for ${flag}`);
        }
    }
    if (client === LUMENFLOW_CLIENT_IDS.CLAUDE_CODE) {
        await integrateClaudeCode(projectDir, { enforcement });
    }
    clearPriorState(projectDir, client);
    return { client, restoredFrom, enforcement };
}
export async function main() {
    const opts = parseEnableOptions();
    const projectDir = process.cwd();
    const result = await enableForClient(projectDir, opts.client);
    if (opts.json) {
        process.stdout.write(JSON.stringify(result, null, 2) + '\n');
        return;
    }
    console.log(`${LOG_PREFIX} Enabled enforcement for ${result.client} (restored from ${result.restoredFrom}).`);
}
if (import.meta.main) {
    void runCLI(main);
}
//# sourceMappingURL=lumenflow-enable.js.map