import path from "node:path";
import { inspectBootstrapTarget } from "./project-detect.js";
import { parseYaml } from "../utils/yaml.js";
import { pathExists, readText } from "../utils/fs.js";
export async function loadProjectOverlay(targetRoot) {
    const projectFile = path.join(targetRoot, ".agent", "project.yaml");
    if (!(await pathExists(projectFile))) {
        return null;
    }
    const raw = await readText(projectFile);
    return parseYaml(raw);
}
export async function resolveProfileSelection(targetRoot, config, explicitProfileName) {
    if (explicitProfileName) {
        return {
            profileName: explicitProfileName,
            profile: resolveProfile(explicitProfileName, config),
            source: "cli"
        };
    }
    const inspection = await inspectBootstrapTarget(targetRoot, config);
    if (inspection.authorityProfileHint && config.routing.profiles[inspection.authorityProfileHint]) {
        return {
            profileName: inspection.authorityProfileHint,
            profile: resolveProfile(inspection.authorityProfileHint, config),
            source: "repo-authority"
        };
    }
    const overlay = await loadProjectOverlay(targetRoot);
    if (overlay?.profile && config.routing.profiles[overlay.profile]) {
        return {
            profileName: overlay.profile,
            profile: resolveProfile(overlay.profile, config),
            source: "repo-local"
        };
    }
    return {
        profileName: config.global.defaults.default_profile,
        profile: resolveProfile(config.global.defaults.default_profile, config),
        source: "fallback-default"
    };
}
export function resolveProfile(name, config) {
    const profile = config.routing.profiles[name];
    if (!profile) {
        throw new Error(`unknown profile: ${name}`);
    }
    return profile;
}
export function resolveExecutionMode(config, selection, overlay, explicitExecutionMode) {
    return (explicitExecutionMode ??
        overlay?.routing?.preferred_execution_mode ??
        selection.profile.default_execution_mode ??
        config.global.defaults.default_execution_mode);
}
export function resolvePrimaryToolOverride(overlay, explicitTool) {
    return explicitTool ?? overlay?.routing?.primary_tool_override;
}
