"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveProfileContinuityInheritance = exports.resolveConfiguredContinuitySourceAccount = void 0;
const fs = __importStar(require("fs"));
const ui_1 = require("../utils/ui");
const instance_manager_1 = __importDefault(require("../management/instance-manager"));
const profile_registry_1 = __importDefault(require("./profile-registry"));
const account_context_1 = require("./account-context");
const shared_resource_policy_1 = require("./shared-resource-policy");
const profile_compat_1 = require("../utils/profile-compat");
const config_loader_facade_1 = require("../config/config-loader-facade");
function loadLegacyContinuityInheritanceMap() {
    const configJsonPath = (0, config_loader_facade_1.getConfigJsonPath)();
    if (!fs.existsSync(configJsonPath)) {
        return {};
    }
    try {
        const raw = fs.readFileSync(configJsonPath, 'utf8');
        const parsed = JSON.parse(raw);
        if (typeof parsed.continuity_inherit_from_account !== 'object' ||
            parsed.continuity_inherit_from_account === null ||
            Array.isArray(parsed.continuity_inherit_from_account)) {
            return {};
        }
        const normalized = {};
        for (const [profileName, accountName] of Object.entries(parsed.continuity_inherit_from_account)) {
            if (typeof accountName !== 'string')
                continue;
            const normalizedProfile = profileName.trim();
            const normalizedAccount = accountName.trim();
            if (!normalizedProfile || !normalizedAccount)
                continue;
            normalized[normalizedProfile] = normalizedAccount;
        }
        return normalized;
    }
    catch (error) {
        console.error((0, ui_1.warn)(`Failed to parse legacy continuity mapping at "${configJsonPath}": ${error.message}`));
        return {};
    }
}
function resolveMappedAccount(profileName, profileType, inheritFromAccount) {
    const candidates = new Set((0, profile_compat_1.getProfileLookupCandidates)(profileName));
    if (profileType === 'settings') {
        candidates.add((0, profile_compat_1.resolveAliasToCanonical)(profileName));
    }
    for (const candidate of candidates) {
        const mapped = inheritFromAccount[candidate];
        if (typeof mapped !== 'string') {
            continue;
        }
        const normalized = mapped.trim();
        if (normalized.length > 0) {
            return normalized;
        }
    }
    const normalizedCandidates = new Set([...candidates].map((candidate) => candidate.trim().toLowerCase()).filter(Boolean));
    for (const [mappedProfileName, mappedAccountName] of Object.entries(inheritFromAccount)) {
        if (!normalizedCandidates.has(mappedProfileName.trim().toLowerCase())) {
            continue;
        }
        const normalized = mappedAccountName.trim();
        if (normalized.length > 0) {
            return normalized;
        }
    }
    return undefined;
}
function resolveConfiguredContinuitySourceAccount(profileName, profileType) {
    const inheritFromAccount = (0, config_loader_facade_1.getContinuityInheritanceMap)();
    return (resolveMappedAccount(profileName, profileType, inheritFromAccount) ??
        (!(0, config_loader_facade_1.isUnifiedMode)()
            ? resolveMappedAccount(profileName, profileType, loadLegacyContinuityInheritanceMap())
            : undefined));
}
exports.resolveConfiguredContinuitySourceAccount = resolveConfiguredContinuitySourceAccount;
/**
 * Resolve optional cross-profile continuity inheritance.
 *
 * Rules:
 * - Claude target only.
 * - Never applies to account profiles.
 * - Mapping source must be an account profile.
 */
async function resolveProfileContinuityInheritance(input) {
    if (input.target !== 'claude' || input.profileType === 'account') {
        return {};
    }
    const sourceAccount = resolveConfiguredContinuitySourceAccount(input.profileName, input.profileType);
    if (!sourceAccount) {
        return {};
    }
    try {
        const registry = new profile_registry_1.default();
        const profiles = registry.getAllProfilesMerged();
        const mappedProfile = profiles[sourceAccount];
        if (!mappedProfile || mappedProfile.type !== 'account') {
            console.error((0, ui_1.warn)(`Continuity inheritance skipped for "${input.profileName}": source "${sourceAccount}" not found or not an account profile`));
            return {};
        }
        const contextPolicy = (0, account_context_1.resolveAccountContextPolicy)((0, account_context_1.isAccountContextMetadata)(mappedProfile) ? mappedProfile : undefined);
        const instanceMgr = new instance_manager_1.default();
        const instancePath = await instanceMgr.ensureInstance(sourceAccount, contextPolicy, {
            bare: (0, shared_resource_policy_1.isProfileLocalSharedResourceMode)(mappedProfile),
        });
        return {
            sourceAccount,
            claudeConfigDir: instancePath,
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error((0, ui_1.warn)(`Continuity inheritance skipped for "${input.profileName}": failed to initialize source "${sourceAccount}" (${message})`));
        return {};
    }
}
exports.resolveProfileContinuityInheritance = resolveProfileContinuityInheritance;
//# sourceMappingURL=profile-continuity-inheritance.js.map