/*
 * Shared bootstrap for the Agency Agent.
 *
 * Sole responsibilities:
 *   - Compute the per-user state directory `$HOME/.agency-agent`.
 *   - Enable persistent memory so each subagent's `remember`/`recall`
 *     calls land in a stable on-disk knowledge graph.
 */
import { registerLocalModel } from "std::agency/local"
import { keys } from "std::object"
import { setLlmOptions, envVarFor } from "std::llm"
import { enableMemory, MemoryConfig } from "std::memory"
import { env } from "std::system"

import {
  resolveCapabilities,
  Capabilities,
  ResolvedCapabilities,
 } from "./lib/capabilities.agency"
import { resolveDetected, knownProviders, missingProviderEnvVar, Resolved } from "./lib/models.agency"
import { resolveAll, buildLayers, Ctx } from "./lib/resolution.agency"
import { resolveAgentHome } from "./lib/config.agency"
import { getCapabilitySettings, getModelSettings, loadSettings } from "./lib/settings.agency"
import { slotKind } from "./lib/slots.agency"


// One-shot runs (--print / piped / a positional query) have no REPL for the
// user to say "keep going", so an autonomous task gets more tool rounds by
// default than the interactive baked default (10).
export static const ONE_SHOT_MAX_TOOL_CALL_ROUNDS = 50

/** Effective maxToolCallRounds for a run. An explicit --max-tool-call-rounds
  always wins; otherwise a one-shot run gets ONE_SHOT_MAX_TOOL_CALL_ROUNDS and
  an interactive run returns null (keep the compiled default). */
export def resolveMaxToolCallRounds(
  explicit: number | null,
  oneShot: boolean,
): number | null {
  if (explicit != null) {
    return explicit
  }
  if (oneShot) {
    return ONE_SHOT_MAX_TOOL_CALL_ROUNDS
  }
  return null
}


// Per-user state directory for the agent (persistent memory + saved
// policy). We expand `~` ourselves via `env("HOME")` because
// `enableMemory(...)`'s underlying `MemoryFrame` calls
// `path.resolve(cwd, dir)` directly — Node's `path.resolve` does NOT
// expand `~`, so passing `"~/.agency-agent/memory"` would silently
// create a literal `./~/.agency-agent/memory` under cwd instead of
// the intended `$HOME/.agency-agent/memory`. Tracked upstream as
// agency-lang#230. Falls back to `.` if `HOME` is unset (rare; mostly
// a Windows concern — the `.` puts the dir under cwd as a last
// resort instead of crashing module init).
export def computeAgentDir(): string {
  // One resolver for the agent home: settings, policy, history, and the
  // memory dir all go through resolveAgentHome, so the sandbox variable
  // and the home fallback cannot drift between them.
  return resolveAgentHome(env("AGENCY_AGENT_HOME"))
}

export static const AGENCY_AGENT_DIR = computeAgentDir()

// Persistent knowledge graph for every subagent. `setMemoryId(...)`
// (called inside std::agent's router) scopes which graph their
// `remember`/`recall` calls hit, so a single shared on-disk directory
// cleanly hosts both. `main()` calls this once, AFTER resolving the model,
// so it can be skipped for `--local-model`: the llama-cpp provider has no
// embedding endpoint, so enabling memory would only emit a one-time
// "Tier-2 disabled" notice and add overhead. All `std::memory` calls
// (`setMemoryId`/`recall`/`remember`) no-op when memory isn't enabled, so a
// local run works fine without it. Calling `enableMemory(...)` from `main()`
// is the documented pattern (see `stdlib/memory.agency`); `with approve`
// auto-approves the dir creation and has the enclosing step path it needs
// inside this def. By default the memory layer derives the embedding
// model from the active LLM provider (openai → text-embedding-3-small,
// google → text-embedding-004, ollama → nomic-embed-text). When the user
// assigned the embedding slot, the caller passes the override and memory
// embeddings run on that model and provider instead.
export def enableAgentMemory(embeddings: (EmbeddingsOverride | null) = null) {
  enableMemory(memoryConfigFor(embeddings)) with approve
}

// The slow ("deep reasoning") model + its provider, set once by
// `configureModels()`. The deep subagents (oracle, explorer) read these.
// An empty slowProvider means "let smoltalk resolve the provider from
// the model name".
let slowModel: string = "gpt-5.6-sol"
let slowProvider: string = "openai-responses"

export def getSlowModel(): string {
  return slowModel
}

export def getSlowProvider(): string {
  return slowProvider
}

// Cache of the last applied assignment, for getResolvedSlots() (the explain
// view + tests) and the cross-provider switch diff.
let _resolved: Record<string, Resolved> = {}

export def setSlowModel(name: string, provider: string) {
  slowModel = name
  slowProvider = provider
}

// The agent always uses the OpenAI Responses API (for hosted web_search), so
// any resolved `openai` provider is promoted to `openai-responses`. The built-in
// defaults already carry this (via planModels); this also covers the
// --model/--provider override paths. Idempotent.
def promoteProvider(provider: string): string {
  if (provider == "openai") {
    return "openai-responses"
  }
  return provider
}

/** Inverse of promoteProvider. Capability tables and settings.json key
  providers by their public name, "openai". The internal openai-responses
  promotion must not leak into either place. If it did, a hand-written
  "openai" entry in settings.json would silently never match. */
export def demoteProvider(provider: string): string {
  if (provider == "openai-responses") {
    return "openai"
  }
  return provider
}


/** The embedding slot's model and provider, demoted. */
export type EmbeddingsOverride = {
  model: string;
  provider: string
}

/** Map one resolved slot value to an embeddings override. Null when the
  value is absent, its model is empty, or its provider is empty. The
  provider comes out demoted as belt-and-braces; promoteAll already
  exempts derived slots, so demotion is normally a no-op here. This is
  the single home of that rule. embeddingsOverride and reactToSlotChange
  both use it. */
export def overrideFromResolved(
  resolved: (Resolved | null),
): (EmbeddingsOverride | null) {
  if (resolved == null || resolved.model == "" || resolved.provider == "") {
    return null
  }
  return {
    model: resolved.model,
    provider: demoteProvider(resolved.provider)
  }
}

/** The embeddings override from the resolved slots, or null. */
export def embeddingsOverride(
  slots: Record<string, Resolved>,
): (EmbeddingsOverride | null) {
  return overrideFromResolved(slots["embedding"])
}

/** True when the provider requires env configuration that is unset —
  the API-key var, or the base-URL var for proxy providers. Providers
  that require nothing never report missing. */
export def providerEnvMissing(provider: string): boolean {
  return missingProviderEnvVar(provider) != ""
}

/** The embedding-key question, answered once. Every checkpoint that
  needs "is the embedding slot usable right now" consumes this instead
  of re-deriving override plus demotion plus key check. */
export type EmbeddingKeyStatus = {
  state: ("no-override" | "key-missing" | "ready");
  override: (EmbeddingsOverride | null);
  varName: string
}

export def embeddingKeyStatus(
  slots: Record<string, Resolved>,
): EmbeddingKeyStatus {
  const override = embeddingsOverride(slots)
  if (override == null) {
    return {
      state: "no-override",
      override: null,
      varName: ""
    }
  }
  const missing = missingProviderEnvVar(override.provider)
  if (missing != "") {
    return {
      state: "key-missing",
      override: override,
      varName: missing
    }
  }
  return {
    state: "ready",
    override: override,
    varName: ""
  }
}

/** Decide how maybeEnableMemory should enable memory. Pure, so the
  branching is testable without the environment or the memory runtime. */
export def memoryEnablePlan(
  memoryOn: boolean,
  status: EmbeddingKeyStatus,
): ("skip" | "enable-default" | "enable-fallback" | "enable-override") {
  if (!memoryOn) {
    return "skip"
  }
  if (status.state == "no-override") {
    return "enable-default"
  }
  if (status.state == "key-missing") {
    return "enable-fallback"
  }
  return "enable-override"
}

/** Build the enableMemory config. Extracted so a test can assert the
  wiring seam: the override reaches the config, and null keeps the
  default shape. */
export def memoryConfigFor(
  embeddings: (EmbeddingsOverride | null),
): MemoryConfig {
  const dir = "${AGENCY_AGENT_DIR}/memory"
  if (embeddings == null) {
    return {
      dir: dir
    }
  }
  return {
    dir: dir,
    embeddings: {
      model: embeddings.model,
      provider: embeddings.provider
    }
  }
}

// Capability profile for the current main model. refreshCapabilities()
// resolves it and getCapabilities() reads it. The key and provider are
// kept so /settings knows what scope "this model" means.
let _capabilities: ResolvedCapabilities = {
  values: {
    prompt: "large",
    summarize: true,
    memory: true,
    maxTokens: 20000
  },
  sources: {
    prompt: "default",
    summarize: "default",
    memory: "default",
    maxTokens: "default"
  }
}
let _capabilityModelKey: string = ""
let _capabilityProvider: string = ""

/** Re-resolve the capability profile for (modelKey, provider) against the
  user's saved overrides and cache it. Demotes the provider first.

  Two callers: applyResolved covers the hosted path and /model switches.
  configureLocalModel calls it again with the curated short name, because
  the .gguf path applyResolved sees would miss MODEL_CAPABILITIES entries. */
export def refreshCapabilities(modelKey: string, provider: string) {
  const demoted = demoteProvider(provider)
  const settings = loadSettings()
  _capabilities = resolveCapabilities(
    modelKey,
    demoted,
    getCapabilitySettings(settings),
  )
  _capabilityModelKey = modelKey
  _capabilityProvider = demoted
}

export def getCapabilities(): Capabilities {
  return _capabilities.values
}

export def getCapabilitiesResolved(): ResolvedCapabilities {
  return _capabilities
}

export def getCapabilityModelKey(): string {
  return _capabilityModelKey
}

export def getCapabilityProvider(): string {
  return _capabilityProvider
}

export def promoteAll(
  slots: Record<string, Resolved>,
): Record<string, Resolved> {
  let promoted: Record<string, Resolved> = {}
  for (slot in Object.keys(slots)) {
    const resolved = slots[slot]
    if (resolved == null) {
      continue
    }
    // The promotion exists for chat calls, which need the Responses API
    // for hosted web search. A derived slot names an embed endpoint, so
    // it keeps its public provider name.
    if (slotKind(slot) == "derived") {
      promoted[slot] = resolved
      continue
    }
    promoted[slot] = {
      model: resolved.model,
      provider: promoteProvider(resolved.provider),
      via: resolved.via
    }
  }
  return promoted
}

/** Apply a resolved assignment. Dispatch on SLOT_KIND so adding a slot is a
  data edit, not another branch. `derived` (embedding) is a deliberate no-op —
  memory derives its own embed model from the active provider. Caches the
  applied slots for getResolvedSlots(). */
export def applyResolved(slots: Record<string, Resolved>) {
  _resolved = slots
  for (slot in Object.keys(slots)) {
    const resolved = slots[slot]
    if (resolved == null) {
      continue
    }
    const kind = slotKind(slot)
    if (kind == "fast") {
      setLlmOptions(
        {
        model: resolved.model,
        provider: resolved.provider
      },
      )
    } else if (kind == "slow") {
      setSlowModel(resolved.model, resolved.provider)
    }
  }
  const mainSlot = slots["main"]
  if (mainSlot != null) {
    refreshCapabilities(mainSlot.model, mainSlot.provider)
  }
}

export def getResolvedSlots(): Record<string, Resolved> {
  return _resolved
}

export def currentProvider(): string {
  const main = _resolved["main"]
  if (main != null) {
    return main.provider
  }
  return slowProvider
}

/** Resolve and apply the agent's models from CLI flag values (each
 *  already normalized to "" when absent). The fast model becomes the
 *  run-wide default; the slow model is stored for the deep subagents.
 *  Explicit model flags win; an explicit `--provider` for a recognized
 *  provider selects that provider's default models and skips env
 *  auto-detection; otherwise a provider is detected from API-key env
 *  vars. Exits the process with a printed message on any unresolvable
 *  combination (no key, missing key for a forced provider, or a custom
 *  `--provider` with no model). Resolution logic lives in
 *  `lib/models.agency`; this shell just applies the result. */
export def configureModels(
  model: string,
  fast: string,
  slow: string,
  embedding: string,
  provider: string,
) {
  const settings = getModelSettings(loadSettings())

  // A saved provider preference (settings.model.provider) acts like --provider
  // (a forced provider that skips env auto-detection); an explicit --provider
  // still wins, and env auto-detection is the fallback when neither is set.
  let effectiveProvider = provider
  if (effectiveProvider == "" && settings.provider != null && settings.provider != "") {
    effectiveProvider = settings.provider
  }

  const detected = resolveDetected(model, fast, slow, effectiveProvider)
  if (isFailure(detected)) {
    print(detected.error)
    process.exit(1)
    return
  }

  // CLI flags become layers: --model is a global pin; --fastmodel/--slowmodel
  // are per-slot overrides. Settings (settings.json model.slots/pin) sit below
  // CLI. The built-in price-default fills anything unset. See spec 3.3.
  const ctx: Ctx = {
    provider: detected.value,
    price: "standard"
  }
  let cliSlots: Record<string, string> = {}
  if (embedding != "") {
    cliSlots["embedding"] = embedding
  }
  if (fast != "") {
    cliSlots["main"] = fast
  }
  if (slow != "") {
    cliSlots["reasoning"] = slow
  }

  // providerEstablished is true when a provider is fixed (CLI or settings) so
  // parseModelSpec will not split a unified provider/model and override it.
  const providerEstablished = effectiveProvider != ""
  const layers = buildLayers(
    "",
    {},
    model,
    cliSlots,
    settings,
    knownProviders(),
    providerEstablished,
  )
  const all = resolveAll(layers, ctx)
  if (isFailure(all)) {
    print(all.error)
    process.exit(1)
    return
  }
  applyResolved(promoteAll(all.value))
}

/** Apply a local model (from `--local-model`) as BOTH the fast and slow
 *  model: register the llama-cpp provider, download the model if needed into
 *  the agent's models cache, and point every LLM call — including the deep
 *  subagents — at it, so a fully-local run needs no hosted-provider key. */
export def configureLocalModel(value: string) {
  // `try` captures any failure (smoltalk-llama-cpp not installed, an unknown
  // model name, a download error) as a Result instead of letting the runtime
  // convert the throw to a Failure and silently continue into the REPL. A
  // local-model setup failure is fatal: print it and exit, mirroring how
  // `configureModels` exits on an unresolvable provider.
  // No explicit cache dir: use the shared default (AGENCY_MODELS_DIR env,
  // else agency.json client.modelsDir, else ~/.agency-agent/models) so a CLI
  // `agency local download` and the agent reuse the same downloaded models.
  const result = try registerLocalModel(value)
  if (isFailure(result)) {
    print(result.error)
    process.exit(1)
    return
  }
  const modelPath = result.value
  // Local pins every slot to the one llama-cpp model. Route through
  // applyResolved so getResolvedSlots() reflects it (the explain view + the
  // /local recall diff). Embedding is empty — llama-cpp has no embed endpoint.
  const r: Resolved = {
    model: modelPath,
    provider: "llama-cpp",
    via: "local"
  }
  applyResolved(
    {
    main: r,
    reasoning: r,
    embedding: {
      model: "",
      provider: "llama-cpp",
      via: "local"
    }
  },
  )
  // applyResolved keyed capabilities by the resolved .gguf path. Re-key
  // by the curated short name so MODEL_CAPABILITIES entries match.
  refreshCapabilities(value, "llama-cpp")
}

