"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createIntegrationCommand = createIntegrationCommand;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const workspace_ignore_1 = require("../../../lib/workspace-ignore");
const registration_1 = require("../registration");
function renderPreviewText(plan) {
    return [
        'Ignore Integration Preview',
        `Target: ${plan.target}`,
        `Policy: ${plan.policy.id} (v${plan.policy.version})`,
        `File: ${plan.precondition.path}`,
        `Precondition: ${plan.precondition.exists ? 'existing' : 'missing'}; sha256=${plan.precondition.sha256}; bytes=${plan.precondition.byteLength}`,
        ...plan.mutations.map((mutation) => `${mutation.category}: ${mutation.field} = ${JSON.stringify(mutation.value)}`),
        `Assumptions: ${plan.assumptions.length === 0 ? 'None.' : plan.assumptions.join(' | ')}`,
        'Boundary: preview is read-only; no editor settings or Day Shift state were changed.',
    ].join('\n');
}
async function createIntegrationPreviewCommand() {
    const { Command } = await import('commander');
    return new Command('preview')
        .description('Preview exact target-specific ignore mutations without writing workspace files.')
        .requiredOption('--target <target>', 'Supported integration target (vscode).')
        .action((_, command) => {
        const format = (0, output_1.resolveOutputFormat)(command.parent?.parent?.parent?.opts?.().format);
        if (format === null)
            throw (0, errors_1.createUsageError)('Output format must be one of: text, json.');
        const options = command.opts();
        if (options.target !== 'vscode')
            throw (0, errors_1.createUsageError)(`Unsupported ignore integration target: ${options.target}.`, [
                'Supported targets: vscode',
            ]);
        const context = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const settingsPath = node_path_1.default.join(context.root, '.vscode', 'settings.json');
        const settingsContent = node_fs_1.default.existsSync(settingsPath) ? node_fs_1.default.readFileSync(settingsPath) : undefined;
        const plan = (0, workspace_ignore_1.createVscodeIgnoreIntegrationPlan)({
            policy: (0, workspace_ignore_1.createIgnorePolicy)({ workspaceRoot: context.root }),
            settingsContent,
        });
        (0, output_1.emitSuccess)({ command: 'ignore integration preview', format, data: plan, text: renderPreviewText(plan) });
    });
}
function renderApplyText(result) {
    return [
        'Ignore Integration Apply',
        `Target: ${result.target}`,
        `File: ${result.files.join(', ')}`,
        `Fields: ${result.fields.join(', ')}`,
        `Changed: ${result.changed ? 'yes' : 'no'}`,
        `Before: sha256=${result.before.sha256}; bytes=${result.before.byteLength}`,
        `After: sha256=${result.after.sha256}; bytes=${result.after.byteLength}`,
        `Receipt: ${result.mutation.planHash}; outcome=${result.mutation.outcome}`,
        `Rollback: restore the supplied restorationContent at ${result.rollback.path}${result.rollback.existed ? '' : ' or remove the newly created file'}.`,
        'Next action: reload the VS Code window, then rebuild affected search or language-service indexes if needed.',
        'Boundary: this receipt verifies only the settings mutation; editor, extension-host, and language-server health were not verified.',
    ].join('\n');
}
async function createIntegrationApplyCommand() {
    const { Command } = await import('commander');
    return new Command('apply')
        .description('Apply previewed target-specific ignore mutations with explicit preconditions.')
        .requiredOption('--target <target>', 'Supported integration target (vscode).')
        .requiredOption('--policy-id <identity>', 'Policy identity reported by preview.')
        .requiredOption('--precondition-sha256 <sha256>', 'Target content SHA-256 reported by preview.')
        .requiredOption('--precondition-bytes <bytes>', 'Target byte length reported by preview.')
        .requiredOption('--precondition-exists <boolean>', 'Whether the target existed during preview (true or false).')
        .action((_, command) => {
        const format = (0, output_1.resolveOutputFormat)(command.parent?.parent?.parent?.opts?.().format);
        if (format === null)
            throw (0, errors_1.createUsageError)('Output format must be one of: text, json.');
        const options = command.opts();
        if (options.target !== 'vscode')
            throw (0, errors_1.createUsageError)(`Unsupported ignore integration target: ${options.target}.`, [
                'Supported targets: vscode',
            ]);
        if (!/^[a-f0-9]{64}$/.test(options.preconditionSha256))
            throw (0, errors_1.createUsageError)('Preview precondition SHA-256 must be 64 lowercase hexadecimal characters.');
        if (!/^(0|[1-9][0-9]*)$/.test(options.preconditionBytes))
            throw (0, errors_1.createUsageError)('Preview precondition byte length must be a non-negative integer.');
        if (options.preconditionExists !== 'true' && options.preconditionExists !== 'false')
            throw (0, errors_1.createUsageError)('Preview precondition existence must be true or false.');
        const context = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const settingsPath = node_path_1.default.join(context.root, '.vscode', 'settings.json');
        const settingsContent = node_fs_1.default.existsSync(settingsPath) ? node_fs_1.default.readFileSync(settingsPath) : undefined;
        const policy = (0, workspace_ignore_1.createIgnorePolicy)({ workspaceRoot: context.root });
        const plan = (0, workspace_ignore_1.createVscodeIgnoreIntegrationPlan)({ policy, settingsContent });
        if (options.policyId !== plan.policy.id)
            throw (0, errors_1.createUsageError)('Ignore integration preview policy identity is stale.');
        if (options.preconditionSha256 !== plan.precondition.sha256 ||
            Number(options.preconditionBytes) !== plan.precondition.byteLength ||
            (options.preconditionExists === 'true') !== plan.precondition.exists)
            throw (0, errors_1.createUsageError)('Ignore integration preview content identity is stale.');
        const result = (0, workspace_ignore_1.applyVscodeIgnoreIntegrationPlan)({ workspaceRoot: context.root, policy, plan });
        (0, output_1.emitSuccess)({ command: 'ignore integration apply', format, data: result, text: renderApplyText(result) });
    });
}
async function createIntegrationCommand() {
    const { Command } = await import('commander');
    const command = new Command('integration').description('Preview or explicitly apply target-specific editor ignore integrations.');
    (0, registration_1.registerCommand)(command, await createIntegrationPreviewCommand());
    (0, registration_1.registerCommand)(command, await createIntegrationApplyCommand());
    return command;
}
