import * as dntShim from "../../_dnt.shims.js";
import { log } from "../../deps.js";
import { getStore } from "./store.js";
const BRANCH_PROFILES_FILE = "branch-profiles.json";
export async function getBranchProfilesPath(configDirOverride) {
    return (await getStore("", configDirOverride)) + BRANCH_PROFILES_FILE;
}
export async function loadBranchProfiles(configDirOverride) {
    try {
        const path = await getBranchProfilesPath(configDirOverride);
        const content = await dntShim.Deno.readTextFile(path);
        return JSON.parse(content);
    }
    catch {
        // File doesn't exist or invalid JSON - return empty mapping
        return { lastUsed: {} };
    }
}
export async function saveBranchProfiles(mapping, configDirOverride) {
    const path = await getBranchProfilesPath(configDirOverride);
    await dntShim.Deno.writeTextFile(path, JSON.stringify(mapping, null, 2));
}
export function getBranchProfileKey(branch, baseUrl, workspaceId) {
    // Normalize baseUrl to ensure consistency
    let normalizedUrl;
    try {
        normalizedUrl = new URL(baseUrl).toString();
    }
    catch {
        // Fallback to non-normalized URL if parsing fails
        normalizedUrl = baseUrl;
    }
    return `${branch}|${normalizedUrl}|${workspaceId}`;
}
export async function getLastUsedProfile(branch, baseUrl, workspaceId, configDirOverride) {
    const mapping = await loadBranchProfiles(configDirOverride);
    const key = getBranchProfileKey(branch, baseUrl, workspaceId);
    return mapping.lastUsed[key];
}
export async function setLastUsedProfile(branch, baseUrl, workspaceId, profileName, configDirOverride) {
    const mapping = await loadBranchProfiles(configDirOverride);
    const key = getBranchProfileKey(branch, baseUrl, workspaceId);
    mapping.lastUsed[key] = profileName;
    await saveBranchProfiles(mapping, configDirOverride);
    log.debug(`Saved last used profile for ${key}: ${profileName}`);
}
