import * as readline from "node:readline";
import { modelSelectionGuidance } from "../cli/model-selection-guidance";
import { initializeProviderModelSelection } from "../providers/initial-model-selection";
import { openUrl } from "../lib/open-url";
import { createBrowserLaunchReport } from "../lib/browser-launch-notice";
import { loadConfig, saveConfig } from "../config";
import { findLiveProxy } from "../server/proxy-liveness";
import {
  requestBoundLocalProviderReload,
  type LocalProviderReloadResult,
} from "../server/local-provider-reload-client";
import { DEPRECATED_OAUTH_PROVIDER_ALIASES, isPublicOAuthProvider, listOAuthProviders, runLogin } from "./index";
import { KEY_LOGIN_PROVIDERS, isKeyLoginProvider, validateApiKey, type KeyLoginProvider } from "./key-providers";
import type { OcxConfig, OcxProviderConfig } from "../types";
import { configuredAdminToken } from "../lib/admin-secrets";
import { codexAccountNamespaceProviderCollisionError } from "../codex/account-namespace-match";

/**
 * Seams a test drives in place of a browser, a terminal and a real provider. Production passes
 * none of them.
 *
 * They exist because the thing worth proving here is an ORDER — that a browser which did not
 * open is on screen before the question that assumes it did — and an order is only observable
 * from something that records both events. Spawning a launcher and attaching to stdin to find
 * that out would test the operating system instead.
 */
export interface LoginCliDeps {
  runLogin?: typeof runLogin;
  openUrl?: typeof openUrl;
  warn?: (message: string) => void;
  /** Ask one question, read one line. Defaults to a readline prompt that owns its own lifetime. */
  ask?: (question: string) => Promise<string>;
}

/**
 * Run `body` with a line reader, creating and closing a real one only when the caller did not
 * supply its own. A readline interface attaches to stdin, so building one that nothing will ask
 * a question keeps the process alive for no reason.
 */
async function withPrompt<T>(
  supplied: ((question: string) => Promise<string>) | undefined,
  body: (ask: (question: string) => Promise<string>) => Promise<T>,
): Promise<T> {
  if (supplied) return await body(supplied);
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  try {
    return await body(question => new Promise<string>(resolve => rl.question(question, resolve)));
  } finally {
    rl.close();
  }
}

const LIVE_RELOAD_PROVIDERS = new Set<string>([
  ...listOAuthProviders(),
  ...Object.keys(KEY_LOGIN_PROVIDERS),
]);

export function runningProxyUpdateHeaders(): Headers {
  const headers = new Headers({ "Content-Type": "application/json" });
  const adminToken = configuredAdminToken();
  if (adminToken) headers.set("X-OpenCodex-API-Key", adminToken);
  return headers;
}

/**
 * Ask the attested runtime to reload one already-persisted provider.
 *
 * Returns the outcome instead of swallowing it. A running proxy that predates
 * attested reload — or one whose runtime record no longer matches — cannot adopt
 * the new credential, and the caller has to say so: the credential is on disk, but
 * the live process keeps routing with the old one until it restarts. Silently
 * printing success there is how a login appears to work and then does not.
 */
export async function notifyRunningProxy(name: string): Promise<LocalProviderReloadResult | null> {
  if (!LIVE_RELOAD_PROVIDERS.has(name)) return null;
  const live = await findLiveProxy();
  if (!live) return null;
  return await requestBoundLocalProviderReload(live, name);
}

/**
 * After `runLogin()` has persisted the merged provider (including preserved apiKey /
 * apiKeyPool / authMode), ask the attested proxy to reload that exact on-disk entry.
 */
export async function notifyRunningProxyAfterOAuthLogin(name: string): Promise<LocalProviderReloadResult | null> {
  if (!loadConfig().providers[name]) return null;
  return await notifyRunningProxy(name);
}

/**
 * A live proxy was found but could not adopt the credential. `null` means there was
 * nothing to notify (no running proxy, or a provider that never reloads live), which
 * is not a warning-worthy state.
 */
export function warnIfLiveReloadSkipped(result: LocalProviderReloadResult | null): void {
  if (!result || result.kind === "reloaded") return;
  console.warn(
    `\n⚠️  A proxy is running but could not reload this provider (${result.reason}).`
    + `\n   The credential is saved to disk; the running proxy keeps using the previous one.`
    + `\n   Restart it to pick this up: ocx restart`,
  );
}

/**
 * The provider wall is the first thing an unfamiliar user sees, so it names the Codex
 * route before the ~90 provider ids. 'codex' is not in either list on purpose: it is
 * routed to the account-pool login in dispatch.ts, and 'chatgpt' stays off the public
 * OAuth surface (isPublicOAuthProvider) because the pool owns that credential.
 *
 * It names 'openai-apikey' for the same reason it exists at all: 'openai' now routes to
 * the pool, so someone who typed it looking for a platform key no longer sees the list
 * that used to be their only pointer to it.
 */
export function loginUsageMessage(): string {
  return `Usage: ocx login <provider>\n`
    + `  Codex / ChatGPT: ocx login codex   (account pool, needs a running proxy; 'chatgpt' and\n`
    + `                   'openai' are the same route. An OpenAI platform key is 'openai-apikey'.)\n`
    + `  OAuth login:   ${listOAuthProviders().join(", ")}\n`
    + `  API-key login: ${Object.keys(KEY_LOGIN_PROVIDERS).join(", ")}`;
}

export async function handleLogin(provider?: string, deps: LoginCliDeps = {}): Promise<void> {
  const name = (provider ?? "").trim().toLowerCase();
  // A removed provider id reached through its alias still logs in — the merged
  // successor owns the flow. Warn rather than silently reroute so scripts and
  // docs that still say `devin-cli` surface the rename to whoever runs them.
  const alias = DEPRECATED_OAUTH_PROVIDER_ALIASES[name];
  if (alias) {
    console.error(`${name} is deprecated; logging in as ${alias}`);
    return handleOAuthLogin(alias, deps);
  }
  if (isPublicOAuthProvider(name)) return handleOAuthLogin(name, deps);
  if (isKeyLoginProvider(name)) return handleKeyLogin(name, deps);
  console.error(loginUsageMessage());
  process.exit(1);
}

export async function handleOAuthLogin(name: string, deps: LoginCliDeps = {}): Promise<void> {
  const login = deps.runLogin ?? runLogin;
  const launch = deps.openUrl ?? openUrl;
  const browser = createBrowserLaunchReport(deps.warn);
  await withPrompt(deps.ask, async (ask) => {
    await login(name, {
      onAuth: ({ url, instructions }) => {
        console.log(`\n🔐 Opening browser for ${name} login...\n${url}\n`);
        if (instructions) console.log(instructions);
        // The controller does not await onAuth, so the launcher's answer cannot be reported from
        // here — this returns long before it arrives. It reports itself instead, and the one
        // thing that could collide with it waits below (#5261).
        browser.track(launch(url));
      },
      onProgress: (m) => console.log(`   ${m}`),
      onManualCodeInput: async () => {
        // "or wait for browser" is a lie if nothing opened, and a warning printed after readline
        // has drawn the prompt lands on the line the user is typing on.
        await browser.settled();
        return await ask("Paste redirect URL or code (or wait for browser): ");
      },
    });
  });
  // A device or polling provider never prompts, so nothing above waited on the launcher. It is
  // still owed an answer before this claims the login worked.
  await browser.settled();
  const reload = await notifyRunningProxyAfterOAuthLogin(name);
  console.log(`\n✅ Logged in to ${name}. Try: ocx sync`);
  for (const line of modelSelectionGuidance(name)) console.log(line);
  warnIfLiveReloadSkipped(reload);
}

export function providerConfigFromKeyLoginProvider(def: KeyLoginProvider, key: string, baseUrlOverride?: string): OcxProviderConfig {
  return {
    adapter: def.adapter,
    baseUrl: baseUrlOverride ?? def.baseUrl,
    apiKey: key,
    ...(def.apiKeyTransport !== undefined ? { apiKeyTransport: def.apiKeyTransport } : {}),
    ...(def.defaultModel ? { defaultModel: def.defaultModel } : {}),
    ...(def.models ? { models: [...def.models] } : {}),
    ...(def.contextWindow !== undefined ? { contextWindow: def.contextWindow } : {}),
    ...(def.modelContextWindows ? { modelContextWindows: { ...def.modelContextWindows } } : {}),
    ...(def.modelMaxInputTokens ? { modelMaxInputTokens: { ...def.modelMaxInputTokens } } : {}),
    ...(def.defaultMaxOutputTokens !== undefined ? { defaultMaxOutputTokens: def.defaultMaxOutputTokens } : {}),
    ...(def.modelMaxOutputTokens ? { modelMaxOutputTokens: { ...def.modelMaxOutputTokens } } : {}),
    ...(def.modelInputModalities ? { modelInputModalities: cloneRecordOfArrays(def.modelInputModalities) } : {}),
    ...(def.reasoningEfforts ? { reasoningEfforts: [...def.reasoningEfforts] } : {}),
    ...(def.modelReasoningEfforts ? { modelReasoningEfforts: cloneRecordOfArrays(def.modelReasoningEfforts) } : {}),
    ...(def.reasoningEffortMap ? { reasoningEffortMap: { ...def.reasoningEffortMap } } : {}),
    ...(def.modelReasoningEffortMap ? { modelReasoningEffortMap: cloneNestedRecord(def.modelReasoningEffortMap) } : {}),
    ...(def.noVisionModels ? { noVisionModels: [...def.noVisionModels] } : {}),
    ...(def.noReasoningModels ? { noReasoningModels: [...def.noReasoningModels] } : {}),
    ...(def.noTemperatureModels ? { noTemperatureModels: [...def.noTemperatureModels] } : {}),
    ...(def.noTopPModels ? { noTopPModels: [...def.noTopPModels] } : {}),
    ...(def.noStopModels ? { noStopModels: [...def.noStopModels] } : {}),
    ...(def.noPenaltyModels ? { noPenaltyModels: [...def.noPenaltyModels] } : {}),
    ...(def.autoToolChoiceOnlyModels ? { autoToolChoiceOnlyModels: [...def.autoToolChoiceOnlyModels] } : {}),
    ...(def.preserveReasoningContentModels ? { preserveReasoningContentModels: [...def.preserveReasoningContentModels] } : {}),
    ...(def.requiresReasoningPlaceholderModels ? { requiresReasoningPlaceholderModels: [...def.requiresReasoningPlaceholderModels] } : {}),
    ...(def.escapeBuiltinToolNames !== undefined ? { escapeBuiltinToolNames: def.escapeBuiltinToolNames } : {}),
  };
}

/**
 * Merge a freshly built key-login provider row with a previously saved row,
 * carrying operator-owned fields the key-provider preset cannot know about.
 * Currently that is the user-configured modelCosts overlay: rotating the API
 * key must not silently revert Logs/Usage estimates to catalog prices.
 */
export function mergeKeyLoginProviderRow(
  provider: OcxProviderConfig,
  existing: OcxProviderConfig | undefined,
): OcxProviderConfig {
  return {
    ...provider,
    ...(existing?.modelCosts !== undefined ? { modelCosts: existing.modelCosts } : {}),
  };
}

/**
 * Commit a fresh key-login provider row: merge operator-owned fields from the
 * existing row (currently the modelCosts overlay), persist the merged row, and
 * push the SAME merged row to a running proxy so its live config cannot diverge
 * from disk (e.g. by replacing the overlay with catalog prices until reload).
 * Returns the merged row that was persisted and notified.
 */
export async function commitKeyLoginProvider(
  config: OcxConfig,
  name: string,
  provider: OcxProviderConfig,
  onLiveReload?: (result: LocalProviderReloadResult | null) => void,
): Promise<OcxProviderConfig> {
  const mergedProvider = mergeKeyLoginProviderRow(provider, config.providers[name]);
  initializeProviderModelSelection(name, mergedProvider, config.providers[name], config);
  config.providers[name] = mergedProvider;
  saveConfig(config);
  // Evaluate the reload BEFORE the optional call: `onLiveReload?.(await ...)` short-circuits
  // the whole argument list when no callback is supplied, so the reload would never fire for
  // callers that do not care about the outcome.
  const reloadResult = await notifyRunningProxy(name);
  onLiveReload?.(reloadResult);
  return mergedProvider;
}

export async function handleKeyLogin(name: string, deps: LoginCliDeps = {}): Promise<void> {
  const def = KEY_LOGIN_PROVIDERS[name];
  const launch = deps.openUrl ?? openUrl;
  const preflightConfig = loadConfig();
  const namespaceCollision = codexAccountNamespaceProviderCollisionError(preflightConfig.codexAccountNamespaces, name);
  if (namespaceCollision) {
    console.error(`Error: ${namespaceCollision}.`);
    process.exit(1);
  }
  console.log(`\n🔑 ${def.label} — opening ${def.dashboardUrl} so you can create/copy an API key...`);
  const browser = createBrowserLaunchReport(deps.warn);
  browser.track(launch(def.dashboardUrl));
  // The next question asks for a key the user gets FROM that page, so a page that never opened
  // has to be on screen before the question rather than underneath it (#5261).
  await browser.settled();
  const { key, baseUrl } = await withPrompt(deps.ask, async (ask) => {
    const entered = (await ask(`Paste your ${def.label} API key: `)).trim();
    // Template URL with placeholders needs resolution before saving.
    let resolvedBaseUrl = def.baseUrl;
    if (/\{[^}]*\}/.test(resolvedBaseUrl)) {
      const resolved = (await ask(`Your endpoint URL (${resolvedBaseUrl}): `)).trim();
      if (!resolved) {
        console.error("A resolved URL is required — replace the {placeholder} with your actual value.");
        process.exit(1);
      }
      resolvedBaseUrl = resolved;
    }
    return { key: entered, baseUrl: resolvedBaseUrl };
  });
  if (!key) {
    console.error("No key entered.");
    process.exit(1);
  }
  process.stdout.write("   validating… ");
  const valid = await validateApiKey(name, { ...def, baseUrl }, key);
  console.log(valid === true ? "valid ✅" : valid === false ? "INVALID ❌" : "couldn't validate (may still work)");
  if (valid === false) {
    console.error("Provider rejected the key. Not saved.");
    process.exit(1);
  }
  const provider = providerConfigFromKeyLoginProvider(def, key, baseUrl);
  const config = loadConfig();
  const commitCollision = codexAccountNamespaceProviderCollisionError(config.codexAccountNamespaces, name);
  if (commitCollision) {
    console.error(`Error: ${commitCollision}.`);
    process.exit(1);
  }
  let reload: LocalProviderReloadResult | null = null;
  await commitKeyLoginProvider(config, name, provider, result => { reload = result; });
  console.log(`✅ ${def.label} added. Try: ocx sync`);
  for (const line of modelSelectionGuidance(name)) console.log(line);
  warnIfLiveReloadSkipped(reload);
}

function cloneRecordOfArrays(input: Record<string, string[]>): Record<string, string[]> {
  return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, [...value]]));
}

function cloneNestedRecord(input: Record<string, Record<string, string>>): Record<string, Record<string, string>> {
  return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, { ...value }]));
}
