/**
 * resolve-missing-inputs.ts — interactive resolution of a required run input
 * that is missing. Covers owner.team for both local runs
 * (`resolveMissingInputs`) and remote dispatch (`resolveRemoteOwnerTeam`),
 * built around one shared need → prompt → persist → apply helper. No registry
 * framework yet — see the spec.
 *
 * See docs/design-docs/cli-interactive-input-resolution.md.
 */
import { setUserConfigKey } from "../../adapters/config-sources/user-config.js";
import { promptOwnerTeam } from "./prompt-owner-team.js";
/**
 * True when a LOCAL run will actually need an owner team and none is resolved.
 * Mirrors the provenance gate's `willPublish` — a publish is intended only
 * when publishing is enabled AND a report store is configured.
 */
export function ownerTeamNeeded(o) {
    return o.publishEnabled && o.reportStoreConfigured && !o.ownerTeamOption;
}
/**
 * Thrown when a remote run needs an owner team but the user declined to pick
 * one. Remote dispatch always requires a team (the API gateway rejects a
 * teamless run) and — unlike a local run — there is no publish to downgrade, so
 * the run cannot continue. The CLI layer catches this and exits cleanly.
 */
export class RemoteOwnerTeamRequiredError extends Error {
    name = "RemoteOwnerTeamRequiredError";
    constructor() {
        super("A remote run requires an owner team, but none was selected.");
    }
}
/** Ask whether to save the team globally or use it for this run only. */
async function promptPersistScope() {
    const { select } = await import("@inquirer/prompts");
    return select({
        message: "Remember this team?",
        choices: [
            { name: "Save for all my projects (global config)", value: "global" },
            { name: "Just for this run", value: "run" },
        ],
    });
}
const DEFAULT_DEPS = {
    promptOwnerTeam,
    promptPersistScope,
    persistTeam: (team) => setUserConfigKey("owner.team", team),
};
/**
 * Prompt for an owner team, optionally persist it to the user-global config,
 * and apply it to `o.ownerTeamOption`. Returns true when a team was set, false
 * when the user skipped. Shared by the local and remote resolution paths.
 */
async function promptPersistApplyTeam(o, deps) {
    const team = await deps.promptOwnerTeam();
    if (!team)
        return false;
    const scope = await deps.promptPersistScope();
    if (scope === "global") {
        // A corrupt prefs file makes setUserConfigKey throw — warn and degrade to
        // this-run-only rather than killing the run over a prefs write.
        try {
            deps.persistTeam(team);
            console.log(`  ✓ Saved owner.team = ${team} to your global config.`);
        }
        catch (err) {
            console.warn(`  ⚠️  Could not save to global config (${err.message}). ` +
                `Using the team for this run only.`);
        }
    }
    o.ownerTeamOption = team;
    return true;
}
/**
 * Fill in a required-but-missing LOCAL run input interactively. Mutates `o` in
 * place (sets `ownerTeamOption`, may flip `publishEnabled`). No-op when the
 * session is non-interactive or `--yes` is set, or when the team is not needed.
 * On skip, downgrades the run to no-publish.
 */
export async function resolveMissingInputs(o, env, deps = DEFAULT_DEPS) {
    if (!env.isTty || env.yes)
        return;
    if (!ownerTeamNeeded(o))
        return;
    const set = await promptPersistApplyTeam(o, deps);
    if (!set) {
        o.publishEnabled = false;
        console.warn("  ⚠️  No team selected — running without publishing. " +
            "Set a team (ailf config set owner.team <slug>) to publish.");
    }
}
/**
 * Resolve the owner team for a REMOTE dispatch. A remote run always needs a
 * team (the API gateway rejects a teamless run), so this prompts whenever none
 * is resolved — independent of the local publish signal. No-op when a team is
 * already set, or when the session is non-interactive / `--yes` (those fall
 * through to the gateway, which the CLI surfaces as a clean error). Throws
 * `RemoteOwnerTeamRequiredError` when the user skips, since a remote run cannot
 * continue without one.
 */
export async function resolveRemoteOwnerTeam(o, env, deps = DEFAULT_DEPS) {
    if (o.ownerTeamOption)
        return;
    if (!env.isTty || env.yes)
        return;
    const set = await promptPersistApplyTeam(o, deps);
    if (!set)
        throw new RemoteOwnerTeamRequiredError();
}
