import { EXPORT_CLIENT_IDS } from "../clients/client-ids";
import { resolveHelpPath } from "./help-catalog";
import type { Capability } from "./capabilities";
import { MODELS_CONTEXT_DETAILS, MODELS_CONTEXT_USAGE } from "./help-models-context";
import { renderRootHelp } from "./help-navigation";
import { formatHelpRecovery } from "./help-recovery";
import { packageVersion as readPackageVersion } from "../lib/package-version";

/**
 * Version of the `ocx` bundle this process is running from.
 *
 * Exported so `status`/`doctor` can compare it against the version the live proxy reports,
 * which is how a stale `ocx` earlier on PATH becomes visible (#2701). Returns `"unknown"`
 * rather than throwing; callers must treat that as "cannot compare", not as a mismatch.
 */
export function packageVersion(): string {
  return readPackageVersion();
}

export function printVersion(): void {
  console.log(`opencodex ${packageVersion()}`);
}

export function printUsage(): void {
  console.log(renderRootHelp());
}

export function printFullUsage(): void {
  console.log(`opencodex (ocx) — Universal provider proxy for Codex

Usage:
  ocx setup                   Interactive setup (alias: init)
  ocx start [--port <port>] [--socks5 [host:port] | --socks5-off]
                              Start the proxy; SOCKS5 defaults to 127.0.0.1:10808
  ocx stop [--json]           Stop the proxy AND restore native Codex (plain codex works again)
  ocx restore                 Restore native Codex without stopping (alias: eject)
  ocx restore back            Re-point codex at the running proxy (undo restore)
  ocx restore --remove-codex-provider-table
                              Also drop [model_providers.opencodex] that a paginated restore kept
  ocx recover-history --legacy-openai --yes
                               Force all user-message opencodex rows to OpenAI (legacy recovery)
  ocx recover-history --ocx-compaction <thread-id> --yes
                               Back up and make one ocx1-compacted thread replayable by native Codex
  ocx uninstall               Remove service/shim/config and restore native Codex (alias: remove)
  ocx service [sub]           Run as a background service (default: install if absent, otherwise repair)
  ocx codex-shim <sub>        Auto-start proxy when \`codex\` launches (install|status|uninstall|remove)
  ocx tray <sub>              Windows status tray (install|start|stop|status|uninstall)
  ocx ensure                  Ensure the proxy is running and Codex config/cache are current
  ocx connect <url>           Connect this machine to a remote OpenCodex hub (credential via stdin)
  ocx remote-workspace <sub>  Pair/run an OCX-only remote execution computer
  ocx disconnect              Restore local state and clear the hub connection
  ocx sync [--local-only] [--json] [--restart-codex]  Sync models and linked Children
                              --expect-link <id> | --expect-hub-key <id>: only from that Home/hub key (exit 5 otherwise)
                              --child <id>: only those Children; --restart-children[=app-server | =codex --yes]: restart their Codex
  ocx sync-cache [--restart-codex]
                              Refresh Codex's model cache from the active catalog
  ocx catalog pull <https-url> Install a validated remote catalog and refresh the Codex cache
  ocx status                  Check proxy server status (on a hub: one block with its ports and token source)
  ocx doctor                  Diagnose environment/network issues (WSL, proxy, ChatGPT reachability)
  ocx doctor --reclaim-response-temps
                              Reclaim abandoned response-state temp files (works without a running proxy)
  ocx doctor --recover-zero-byte-coordinator --yes
                              Back up a proven zero-byte Codex coordinator after stopping the proxy
  ocx debug <scope>           provider/usage/injection/claude on|off|status|reset
  ocx login <provider>        OAuth or API-key provider login (ocx login codex for Codex/ChatGPT)
  ocx logout <provider>       Remove a stored OAuth login
  ocx gui [pair [--desktop] --origin <browser-origin> [--json]]
                              Open the dashboard, pair a remote GUI, or authorize local Desktop changes (--desktop)
  ocx hub invite [--json]     Print a ready-to-run \`ocx connect\` line for one more machine
                              (hub only; see \`ocx help hub\` for the one-port topology)
  ocx link <sub>              Machine links over SSH (port|issue|revoke|status|check)
  ocx update [--tag <tag>]    Update opencodex (keeps preview installs on @preview)
  ocx restart                  Stop and restart the proxy
  ocx v2 <sub>                multi_agent_v2 surface (status|on|off|mode|keep-native-v1|threads|mode-hint)
  ocx health [--json]          Check proxy health (exit 0=healthy, 1=not)
  ocx capabilities [--json] [--contracts]  List capabilities and contracts
  ocx ready [--json] [--wait [--timeout <s>]]  Check post-sync readiness (exit 0 only when ready)
  ocx resolve [--json]        Config home, effective port, and liveness (JSON for shells)
  ocx provider <sub>          Providers, connectivity, quota, and selected models
  ocx account <sub>           Accounts, login/reauth, key pools, and quota controls
  ocx models <sub>            Live/custom models, visibility, context, and shadow calls
  ocx alias <sub>             Short names for providers and models (list, set, rm, defaults)
  ocx combo <sub>             Combo routing strategies and failover
  ocx agent <sub>             Subagents, injection, effort caps, and sidecars
  ocx message <sub>           Codex queued messages, explicit SSH peers and foreground ownership
  ocx effort [sub]            Inspect and configure reasoning effort caps and defaults
  ocx fallback <sub>          Turn model or provider fallback off per scope; per-device local fallback
  ocx observe <sub>           Logs, usage, storage, memory, and debug data
  ocx inspect <sub>           Effective config, catalog, analytics, pacing, client-config
  ocx route <sub>             Routing features (to, combo, policy)
  ocx logs [filters]          Alias of ocx observe logs
  ocx usage [--range <today|1d|7d|30d|all>] [--provider <name>] [--model <id>] [--top <1-1000>]
                              Token and estimated-cost report (alias of ocx observe usage)
  ocx storage <sub>           Storage report, cleanup, trash, and the cleanup policy
  ocx memory [--json]         Alias of ocx observe memory
  ocx api-key <sub>           Alias of ocx access key
  ocx access <sub>            External API keys and endpoint information
  ocx api <sub>               Protocol paths: vocabulary, request-path preview, and policy
  ocx export --client <id>    Print a client config wired to the running proxy (${EXPORT_CLIENT_IDS.length} clients)
  ocx integration client <sub> Enable, disable, inspect or roll back a client integration
  ocx grok <sub>              Grok Build model selection and apply
  ocx system <sub>            Runtime settings, startup, sync, OpenCodex updates, and Codex CLI inspection
  ocx config [sub]            Validated configuration show/get/set/import/export
  ocx advisor <status|on|off|set|consent>  Advisor sidecar settings and context-sharing consent
  ocx companion <show|set|reset>  Menu-bar and widget companion usage settings
  ocx telemetry <sub>         Anonymous usage telemetry status, preview, enable, and disable
  ocx lab <sub>               Inspect Lab evidence and control local automation
  ocx codex-provider <sub>    Confirm custom Codex provider routing: status|allow|revoke
  ocx chatgpt <sub>          Experimental app-server shim: launch|restore|status (macOS)
  ocx claude [args...]        Launch Claude Code wired to the proxy (model discovery on)
  ocx claude desktop [sub]    Manage and apply Claude Desktop's four-family profile
  ocx codex [args...]         Launch Codex through the proxy's routing (pass-through when disabled)
  ocx opencode [args...]      Launch opencode wired to the proxy (runtime provider config)
  ocx mcode [args...]         Launch MiniMax Code through its managed provider
  ocx mmx text <sub> [args]   Launch MiniMax CLI text through the proxy
  ocx zcode [sub]             Connect ZCode to the proxy (managed provider)
  ocx commandcode [sub]       Connect Command Code CLI to the proxy (managed provider)
  ocx cmd [sub]               Alias of ocx commandcode
  ocx help [command]          Show help
  ocx --version | -v          Print version

Examples:
  ocx init                    Set up provider and inject into Codex
  ocx start                   Start on default port (10100)
  ocx start --port 8080       Start on custom port
  ocx start --socks5          Outbound via SOCKS5 at 127.0.0.1:10808 (saved)
  ocx start --socks5-off      Clear a saved SOCKS5 outbound proxy
  ocx help service            Show service command help
  ocx help hub                Explain the hub topology, token file, and invites
  ocx sync                    Sync available models to Codex`);
}

export function hasHelpFlag(values: string[]): boolean {
  return values.some(value => value === "--help" || value === "-h" || value === "help");
}

function printCapabilityDetails(capability: Capability, write: (text: string) => void, shown: readonly string[] = []): void {
  if (capability.flags.length) {
    write("\nDeclared flags:");
    for (const flag of capability.flags) {
      write(`  ${flag.name}${flag.value && flag.value !== "boolean" ? ` <${flag.value}>` : ""}${flag.required ? " (required)" : ""}  ${flag.summary}`);
    }
  }
  const details = capability.details?.filter(detail => !shown.includes(detail));
  if (details?.length) write(`\n${details.join("\n")}`);
}

export function printSubcommandUsage(
  name: string | undefined,
  path?: readonly string[],
  options: { fallbackToParent?: boolean; write?: (text: string) => void } = {},
): void {
  const write = options.write ?? console.log;
  const result = resolveHelpPath(path ?? (name ? [name] : []));
  if (result.kind === "unavailable") {
    // Appended flags may follow runtime operands. An explicit `help <path>`
    // requests that exact detail instead, so only the CLI head enables fallback.
    if (options.fallbackToParent && result.parent) {
      printSubcommandUsage(result.parent[0], result.parent, { write });
      return;
    }
    console.error(formatHelpRecovery(result.path));
    process.exit(1);
  }
  if (result.kind === "entry") {
    write(`Usage: ${result.entry.usage}\n\n${result.entry.summary}`);
    if (result.entry.details?.length) write(`\n${result.entry.details.join("\n")}`);
    if (result.capability) printCapabilityDetails(result.capability, write, result.entry.details);
    if (result.children.length) {
      write("\nDeclared commands (incomplete):");
      for (const child of result.children) write(`  ocx help ${child.command.join(" ")}  ${child.summary}`);
    }
    if (result.canonicalName === "models") write("\nContext cap help: ocx help models context");
    if (result.entry.name !== result.canonicalName) write(`\nCanonical help: ocx help ${result.canonicalName}`);
    return;
  }
  if (result.kind === "models-context") {
    write(`Usage:\n${MODELS_CONTEXT_USAGE}\n\n${MODELS_CONTEXT_DETAILS.join("\n")}`);
  } else if (result.kind === "capability") {
    const { capability } = result;
    const heading = capability.usage !== undefined ? `Usage: ${capability.usage}` : `Command: ocx ${result.path.join(" ")}`;
    write(`${heading}\n\n${capability.summary}`);
    printCapabilityDetails(capability, write);
    if (result.children.length) {
      write("\nDeclared commands (incomplete):");
      for (const child of result.children) write(`  ocx help ${child.command.join(" ")}  ${child.summary}`);
    }
    if (capability.usage === undefined) {
      write("\nCapability metadata is incomplete; this is not the full operand grammar.");
    }
  } else {
    write(`Command group: ocx ${result.path.join(" ")}\n\nDeclared commands (incomplete):`);
    for (const child of result.children) write(`  ocx ${child.command.join(" ")}  ${child.summary}`);
  }
  write(`\nParent help: ocx help ${result.path.slice(0, -1).join(" ")}`);
}
