/**
 * CLI entrypoint — PLAN_RELAY_AGENT T5, extended for the native tunnel (PLAN_TUNNEL_AUTOMATION B5).
 * `pair | run | status | install | uninstall`. All side effects (network/FS/tunnel/provision) are
 * injected via `CliDeps` so `runCli` stays pure and offline-testable.
 *
 * `pair <CODE> --install` is the NATIVE zero-touch onboard: P-256 keygen (FIX H-host-2) → CSR →
 * POST /enroll → provision the pinned frpc binary → write frpc.toml → install BOTH units (base-app
 * + agent, base-app env routed to the base-app unit; the agent unit supervises frpc — NOT the old
 * relay `runTunnel` rendezvous) → print `https://<sub>.terminal.<domain>`.
 *
 * `status` prints host_id/subdomain/online ONLY — never key/cert material (INV9).
 */
import type { AgentConfig } from './config/agentConfig.js'
import type { AgentIdentity } from './keys/identity.js'
import type { Keystore } from './keys/keystore.js'
import { assertNativeZone, type InstallOptions } from './service/install.js'
import { subdomainOrigin } from './service/originConfig.js'
import type { EnrollResult } from 'relay-contracts'

export type CliCommand = 'pair' | 'run' | 'status' | 'install' | 'uninstall'
const COMMANDS: readonly CliCommand[] = ['pair', 'run', 'status', 'install', 'uninstall']

export interface CliArgs {
  readonly command: CliCommand
  readonly code?: string
  readonly flags: Readonly<Record<string, string | boolean>>
}

export class CliUsageError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'CliUsageError'
  }
}

/** The non-secret enrollment result the native onboard needs (host id + assigned subdomain). */
export interface NativeEnrollResult {
  readonly hostId: string
  readonly subdomain: string
}

export interface CliDeps {
  loadConfig(): AgentConfig
  openKeystore(stateDir: string): Keystore
  /** Ed25519 identity for the legacy relay path. */
  generateIdentity(): AgentIdentity
  /** P-256 identity for the native frp-client key (FIX H-host-2); private key never leaves the host. */
  generateP256Identity(): AgentIdentity
  /** Legacy relay redemption (Ed25519, E2E rendezvous). */
  redeem(cfg: AgentConfig, code: string, id: AgentIdentity, ks: Keystore): Promise<EnrollResult>
  /** Native enroll: build the P-256 CSR, POST /enroll, store the returned cert; return ids only. */
  enrollNative(
    cfg: AgentConfig,
    code: string,
    id: AgentIdentity,
    ks: Keystore,
  ): Promise<NativeEnrollResult>
  /** Download + verify + place the pinned frpc binary (B3); returns its path. */
  provisionFrpc(cfg: AgentConfig): Promise<string>
  /** Write the native `frpc.toml` for `subdomain` (base-app env is routed via installService). */
  writeFrpcConfig(cfg: AgentConfig, subdomain: string): void
  /** True iff a written native `frpc.toml` exists in `cfg.stateDir` (native-onboard signal). */
  nativeConfigExists(cfg: AgentConfig): boolean
  /** Legacy relay run-loop (Ed25519 WS rendezvous, T10 backoff + T9 heartbeat). */
  runTunnel(cfg: AgentConfig, ks: Keystore): Promise<number>
  /** Native run-loop: supervise the pinned frpc child (restart-on-exit backoff + health probe). */
  superviseFrpc(cfg: AgentConfig, ks: Keystore): Promise<number>
  /** Resolve per-host install inputs (S0 env incl. loopback BIND_HOST, tunnel origin) from env/flags. */
  resolveInstallOptions(): InstallOptions
  installService(cfg: AgentConfig, options: InstallOptions): Promise<void>
  uninstallService(): Promise<void>
  print(line: string): void
}

/** Parse argv (already sliced past node/script) into a typed CliArgs. */
export function parseArgs(argv: readonly string[]): CliArgs {
  const [command, ...rest] = argv
  if (command === undefined || !COMMANDS.includes(command as CliCommand)) {
    throw new CliUsageError(`unknown command '${command ?? ''}' (expected ${COMMANDS.join(' | ')})`)
  }
  const flags: Record<string, string | boolean> = {}
  const positionals: string[] = []
  for (const token of rest) {
    if (token.startsWith('--')) {
      const [k, v] = token.slice(2).split('=')
      flags[k!] = v ?? true
    } else {
      positionals.push(token)
    }
  }
  const args: CliArgs = { command: command as CliCommand, flags }
  if (command === 'pair') {
    const code = positionals[0]
    if (code === undefined) throw new CliUsageError('usage: web-terminal-agent pair <CODE>')
    return { ...args, code }
  }
  return args
}

/**
 * Native zero-touch onboard for `pair <CODE> --install` (B5). Order is load-bearing: keygen(P-256)
 * → enroll (CSR + POST /enroll) → provision frpc (so the binary exists before the agent unit
 * starts) → write frpc.toml → install BOTH units (which start them) → print the tunnel URL.
 */
async function pairInstallNative(
  code: string,
  cfg: AgentConfig,
  ks: Keystore,
  deps: CliDeps,
): Promise<number> {
  const options = deps.resolveInstallOptions()
  if (!options.domain) {
    throw new CliUsageError(
      'native install requires TUNNEL_DOMAIN — the origin is https://<sub>.terminal.<domain>',
    )
  }
  assertNativeZone(options.zone) // FIX L-host-zone: native ⇒ `terminal`

  const id = deps.generateP256Identity() // keygen (P-256, FIX H-host-2)
  ks.saveIdentity(id)
  const enroll = await deps.enrollNative(cfg, code, id, ks) // CSR → POST /enroll → store cert
  await deps.provisionFrpc(cfg) // pinned frpc binary on disk before the service starts (B3)
  deps.writeFrpcConfig(cfg, enroll.subdomain) // frpc.toml
  await deps.installService(cfg, options) // base-app + agent units; base-app env routed → started

  deps.print(subdomainOrigin(enroll.subdomain, options.domain, options.zone))
  return 0
}

/** Dispatch a parsed CliArgs; returns a process exit code (0 = success). */
export async function runCli(args: CliArgs, deps: CliDeps): Promise<number> {
  const cfg = deps.loadConfig()
  const ks = deps.openKeystore(cfg.stateDir)
  switch (args.command) {
    case 'pair': {
      if (args.flags['install']) return pairInstallNative(args.code!, cfg, ks, deps)
      // Legacy relay pair (Ed25519 rendezvous, no install).
      const id = ks.loadIdentity() ?? deps.generateIdentity()
      ks.saveIdentity(id)
      const enroll = await deps.redeem(cfg, args.code!, id, ks)
      deps.print(`paired: host ${enroll.hostId} subdomain ${enroll.subdomain}`)
      return 0
    }
    case 'run': {
      const id = ks.loadIdentity()
      if (id === null || ks.loadCert() === null) {
        throw new CliUsageError('not enrolled — run `web-terminal-agent pair <CODE>` first')
      }
      // Native onboard = a P-256 frp-client identity + a written frpc.toml. Supervise frpc as a
      // child (restart-on-exit backoff + health probe) instead of the legacy Ed25519 relay tunnel.
      if (id.alg === 'p256' && deps.nativeConfigExists(cfg)) {
        return deps.superviseFrpc(cfg, ks)
      }
      return deps.runTunnel(cfg, ks)
    }
    case 'status': {
      const enrolled = ks.loadIdentity() !== null && ks.loadCert() !== null
      // INV9: print only non-secret identifiers.
      deps.print(`enrolled: ${enrolled}`)
      deps.print(`host_id: ${cfg.hostId ?? '(none)'}`)
      deps.print(`subdomain: ${cfg.subdomain ?? '(none)'}`)
      return 0
    }
    case 'install':
      await deps.installService(cfg, deps.resolveInstallOptions())
      return 0
    case 'uninstall':
      await deps.uninstallService()
      return 0
  }
}
