"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLicenseCleanupRemindersCommand = createLicenseCleanupRemindersCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const artifact_reminder_1 = require("../../../lib/license/artifact-reminder");
const license_guidance_1 = require("../../../lib/license/license-guidance");
const license_resolution_1 = require("../../../lib/license/license-resolution");
const global_format_1 = require("../global-format");
async function createLicenseCleanupRemindersCommand() {
    const { Command } = await import("commander");
    const command = new Command("cleanup-reminders");
    command
        .description("Remove Day Shift-managed license reminder regions after a suppressing license is available.")
        .option("--license-file <path>", "Use a license file for this cleanup run without writing config.")
        .option("--dry-run", "Report reminder cleanup changes without writing files.")
        .addHelpText("after", [
        "",
        "Commercial guidance:",
        ...(0, license_guidance_1.renderLicenseCleanupGuidanceLines)().map((line) => `  ${line}`)
    ].join("\n"))
        .action((...actionArgs) => {
        const commandInstance = actionArgs.at(-1);
        const requestedFormat = commandInstance.optsWithGlobals?.().format ?? (0, global_format_1.getGlobalFormat)(commandInstance);
        const format = (0, output_1.resolveOutputFormat)(requestedFormat);
        if (format === null) {
            throw (0, errors_1.createUnsupportedOutputFormatError)({
                received: requestedFormat,
                commandBoundary: "license cleanup-reminders command output format"
            });
        }
        const commandOptions = commandInstance.opts();
        const repositoryDetection = (0, runtime_contract_1.detectRepositoryRoot)();
        const repositoryContext = (0, runtime_contract_1.createRepositoryContext)(repositoryDetection, false);
        const licenseStatus = (0, license_resolution_1.resolveLicenseStatus)({
            repositoryContext,
            licenseFile: commandOptions.licenseFile
        });
        const cleanupResult = licenseStatus.suppresses_reminders
            ? (0, artifact_reminder_1.cleanupPlanningLicenseReminders)({
                repositoryRoot: repositoryContext.root,
                dryRun: commandOptions.dryRun
            })
            : createUnauthorizedCleanupResult(repositoryContext.root, commandOptions.dryRun);
        const data = createLicenseCleanupRemindersCommandData(licenseStatus, cleanupResult);
        (0, output_1.emitSuccess)({
            command: "license cleanup-reminders",
            format,
            text: renderLicenseCleanupRemindersText(data),
            data
        });
        getRootCommand(commandInstance ?? command).runtimeExitCode =
            data.exit_code === 0 ? errors_1.RuntimeExitCode.SUCCESS : errors_1.RuntimeExitCode.ERROR;
    });
    return command;
}
function createUnauthorizedCleanupResult(repositoryRoot, dryRun) {
    return {
        planningRoot: `${repositoryRoot}/.day-shift/planning`,
        dryRun: dryRun === true,
        changed: false,
        changedPaths: [],
        operations: [],
        scannedFileCount: 0
    };
}
function createLicenseCleanupRemindersCommandData(status, cleanup) {
    const authorized = status.suppresses_reminders;
    const noChangeMessage = cleanup.dryRun
        ? "Dry run found no managed license reminders to remove."
        : "No managed license reminders were found.";
    return {
        authorized,
        dry_run: cleanup.dryRun,
        changed: authorized && cleanup.changed,
        changed_paths: cleanup.changedPaths,
        operations: cleanup.operations,
        scanned_file_count: cleanup.scannedFileCount,
        planning_root: cleanup.planningRoot,
        license_path: status.license_path,
        effective_status: status.effective_status,
        reason_code: status.reason_code,
        suppresses_reminders: status.suppresses_reminders,
        purchase_url: artifact_reminder_1.OFFICIAL_DAY_SHIFT_LICENSE_PURCHASE_URL,
        message: authorized
            ? cleanup.changed
                ? cleanup.dryRun
                    ? "Dry run found managed license reminders that would be removed."
                    : "Managed license reminders were removed."
                : noChangeMessage
            : `A valid Day Shift license is required before cleanup can modify files. Purchase: ${artifact_reminder_1.OFFICIAL_DAY_SHIFT_LICENSE_PURCHASE_URL}`,
        exit_code: authorized ? 0 : 2
    };
}
function renderLicenseCleanupRemindersText(data) {
    return [
        (0, output_1.renderTerminalSection)({
            heading: "License reminder cleanup",
            headingStyle: "title",
            fields: [
                { label: "Authorized", value: data.authorized },
                { label: "Suppresses reminders", value: data.suppresses_reminders },
                { label: "Effective status", value: data.effective_status },
                { label: "Reason code", value: data.reason_code },
                { label: "Dry run", value: data.dry_run },
                { label: "Changed", value: data.changed },
                { label: "Planning root", value: data.planning_root },
                { label: "License path", value: data.license_path },
                { label: "Scanned files", value: data.scanned_file_count },
                { label: "Exit code", value: data.exit_code },
                { label: "Message", value: data.message }
            ]
        }),
        (0, output_1.renderTerminalCompactList)({
            heading: "Changed paths",
            headingStyle: "section",
            entries: data.operations.map((operation) => ({
                label: operation.path,
                fields: [
                    { label: "Action", value: operation.action },
                    { label: "Removed managed regions", value: operation.removedRegionCount }
                ]
            })),
            emptyMessage: "No changed paths."
        }),
        data.authorized
            ? ""
            : (0, output_1.renderTerminalSection)({
                heading: "Commercial guidance",
                headingStyle: "section",
                lines: (0, license_guidance_1.renderLicenseCleanupGuidanceLines)(data.purchase_url)
            }),
        renderCleanupBoundary(data)
    ].filter((section) => section.length > 0).join("\n\n");
}
function renderCleanupBoundary(data) {
    if (!data.authorized) {
        return (0, output_1.renderTerminalBoundary)({
            kind: "no-write-failure",
            reason: "valid suppressing license required"
        });
    }
    if (data.dry_run) {
        return (0, output_1.renderTerminalBoundary)({ kind: "dry-run" });
    }
    if (data.changed) {
        return (0, output_1.renderTerminalBoundary)({
            kind: "write-applied",
            target: `${data.changed_paths.length} changed path(s)`,
            targetLabel: "Cleanup result",
            stateSurface: data.planning_root
        });
    }
    return (0, output_1.renderTerminalBoundary)({
        kind: "mutating-no-op",
        reason: "no managed license reminders found",
        target: data.planning_root,
        targetLabel: "Planning root"
    });
}
function getRootCommand(commandInstance) {
    let current = commandInstance;
    while (current.parent !== undefined && current.parent !== null) {
        current = current.parent;
    }
    return current;
}
