"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleBackup = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const errors_1 = require("../../errors");
const exit_codes_1 = require("../../errors/exit-codes");
const resume_lane_diagnostics_1 = require("../resume-lane-diagnostics");
const account_context_1 = require("../account-context");
const shared_resource_policy_1 = require("../shared-resource-policy");
const types_1 = require("./types");
function copyDirectoryIfPresent(sourcePath, targetPath) {
    if (!fs.existsSync(sourcePath)) {
        return false;
    }
    fs.cpSync(sourcePath, targetPath, {
        recursive: true,
        dereference: true,
        force: false,
        errorOnExist: false,
    });
    return true;
}
async function handleBackup(ctx, args) {
    await (0, ui_1.initUI)();
    const parsed = (0, types_1.parseArgs)(args);
    const { profileName, json } = parsed;
    (0, types_1.rejectUnsupportedAuthOptions)(parsed, {
        usage: 'ccs auth backup <profile|default> [--json]',
    });
    if (!profileName) {
        console.log((0, ui_1.fail)('Profile name is required'));
        console.log('');
        console.log(`Usage: ${(0, ui_1.color)('ccs auth backup <profile|default> [--json]', 'command')}`);
        (0, errors_1.exitWithError)('Profile name is required', exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    try {
        let sourceConfigDir = '';
        let backupLabel = profileName;
        let artifactNames = [];
        if (profileName === 'default') {
            const lane = await (0, resume_lane_diagnostics_1.resolveRuntimePlainCcsResumeLane)();
            sourceConfigDir = lane.configDir;
            backupLabel = lane.accountName ? `default-${lane.accountName}` : 'default';
            artifactNames = (0, resume_lane_diagnostics_1.getContinuityArtifactNames)('default');
        }
        else {
            const profiles = ctx.registry.getAllProfilesMerged();
            const profile = profiles[profileName];
            if (!profile || profile.type !== 'account') {
                (0, errors_1.exitWithError)(`Backup supports auth accounts or "default". Not found: ${profileName}`, exit_codes_1.ExitCode.PROFILE_ERROR);
            }
            const contextPolicy = (0, account_context_1.resolveAccountContextPolicy)((0, account_context_1.isAccountContextMetadata)(profile) ? profile : undefined);
            sourceConfigDir = await ctx.instanceMgr.ensureInstance(profileName, contextPolicy, {
                bare: (0, shared_resource_policy_1.isProfileLocalSharedResourceMode)(profile),
            });
            artifactNames = (0, resume_lane_diagnostics_1.getContinuityArtifactNames)('account');
        }
        const backupRoot = path.join((0, resume_lane_diagnostics_1.getAuthBackupRoot)(), backupLabel, (0, resume_lane_diagnostics_1.createTimestampStamp)());
        fs.mkdirSync(backupRoot, { recursive: true, mode: 0o700 });
        const copied = [];
        const skipped = [];
        for (const artifactName of artifactNames) {
            const sourcePath = path.join(sourceConfigDir, artifactName);
            const targetPath = path.join(backupRoot, artifactName);
            if (copyDirectoryIfPresent(sourcePath, targetPath)) {
                copied.push(artifactName);
            }
            else {
                skipped.push(artifactName);
            }
        }
        const manifest = {
            target: profileName,
            source_config_dir: sourceConfigDir,
            created_at: new Date().toISOString(),
            copied,
            skipped,
        };
        fs.writeFileSync(path.join(backupRoot, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, {
            encoding: 'utf8',
            mode: 0o600,
        });
        if (json) {
            console.log(JSON.stringify({
                target: profileName,
                backup_path: backupRoot,
                copied,
                skipped,
            }, null, 2));
            return;
        }
        console.log((0, ui_1.ok)(`Continuity backup created: ${backupRoot}`));
        console.log('');
        console.log((0, ui_1.info)(`Source lane: ${sourceConfigDir}`));
        console.log(`  ${(0, ui_1.dim)(`Copied: ${copied.length > 0 ? copied.join(', ') : 'none'}`)}`);
        if (skipped.length > 0) {
            console.log(`  ${(0, ui_1.dim)(`Skipped: ${skipped.join(', ')}`)}`);
        }
        console.log('');
    }
    catch (error) {
        (0, errors_1.exitWithError)(`Failed to create continuity backup: ${error.message}`, exit_codes_1.ExitCode.GENERAL_ERROR);
    }
}
exports.handleBackup = handleBackup;
//# sourceMappingURL=backup-command.js.map