import { existsSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import process from 'node:process'

const HOME = homedir()

/** Resolve the OpenThomas home directory. Honors an explicit override
 *  (`OPENTHOMAS_HOME`, or the legacy `THOMAS_HOME`); otherwise prefers
 *  `~/.openthomas` but transparently keeps using a pre-existing `~/.thomas`
 *  so upgraders from the Thomas-branded releases never lose their wiring,
 *  traces, or config — no manual migration required. */
function resolveHome(): string {
  const override = process.env.OPENTHOMAS_HOME ?? process.env.THOMAS_HOME
  if (override) return override
  const next = join(HOME, '.openthomas')
  const legacy = join(HOME, '.thomas')
  if (existsSync(next)) return next
  if (existsSync(legacy)) return legacy
  return next
}

export const OPENTHOMAS_HOME = resolveHome()
/** Back-compat alias — internal call sites still import `THOMAS_HOME`. */
export const THOMAS_HOME = OPENTHOMAS_HOME

export const paths = {
  home: THOMAS_HOME,
  wire: {
    dir: join(THOMAS_HOME, 'wire'),
    routes: join(THOMAS_HOME, 'wire', 'routes.json'),
    traces: join(THOMAS_HOME, 'wire', 'traces'),
    // Cold per-day archive files (YYYY-MM-DD.db) written when prune evicts
    // old data from the active store, so nothing is lost on retention.
    tracesArchive: join(THOMAS_HOME, 'wire', 'traces', 'archive'),
    daemonSock: join(THOMAS_HOME, 'wire', 'daemon.sock'),
  },
  backups: {
    dir: join(THOMAS_HOME, 'backups'),
    manifest: join(THOMAS_HOME, 'backups', 'manifest.json'),
  },
  logs: {
    dir: join(THOMAS_HOME, 'logs'),
    daemon: join(THOMAS_HOME, 'logs', 'daemon.log'),
    daemonErr: join(THOMAS_HOME, 'logs', 'daemon.err'),
  },
  config: join(THOMAS_HOME, 'config.json'),
  update: join(THOMAS_HOME, 'update.json'),
  // Model routing & combos — see core/model-registry.ts, routing-policy.ts.
  models: join(THOMAS_HOME, 'models.json'),
  routing: join(THOMAS_HOME, 'routing.json'),
  secrets: join(THOMAS_HOME, 'secrets.json'),
  // Tool providers (web_search backends, etc.) — see core/tool-providers.ts.
  // The thomas-tools MCP server reads this file at request time to decide
  // which backend to use for each capability.
  toolProviders: join(THOMAS_HOME, 'tool-providers.json'),
  agent: {
    claudeCode: {
      settings: join(HOME, '.claude', 'settings.json'),
      legacy: join(HOME, '.claude.json'),
    },
    claudeDesktop: {
      root: join(HOME, 'Library', 'Application Support', 'Claude'),
      mcpConfig: join(
        HOME,
        'Library',
        'Application Support',
        'Claude',
        'claude_desktop_config.json',
      ),
    },
    openclaw: join(HOME, '.openclaw', 'openclaw.json'),
    opencode: join(HOME, '.config', 'opencode', 'opencode.json'),
    hermes: {
      config: join(HOME, '.hermes', 'config.yaml'),
      env: join(HOME, '.hermes', '.env'),
    },
    codex: {
      config: join(HOME, '.codex', 'config.toml'),
      auth: join(HOME, '.codex', 'auth.json'),
    },
    cursor: {
      darwin: join(HOME, 'Library', 'Application Support', 'Cursor', 'User', 'settings.json'),
      linux: join(HOME, '.config', 'Cursor', 'User', 'settings.json'),
    },
    gemini: join(HOME, '.gemini', '.env'),
  },
} as const

export const PRICING_OVERRIDE = join(THOMAS_HOME, 'pricing.json')

// Runtime-refreshed pricing catalog overlay (models.dev), written by the
// opt-in auto-refresh loop. Distinct from the bundled catalog.json shipped
// in the package — this one, when present, takes precedence so prices stay
// fresh without a Thomas upgrade. Off by default (config.autoRefreshPricing).
export const PRICING_CATALOG_CACHE = join(THOMAS_HOME, 'pricing-catalog.json')

// Port override exists for tests (smoke test spins a daemon on a throwaway
// port so it never collides with the user's real daemon on 9877). Legacy
// THOMAS_PORT still honored.
export const DAEMON_PORT = (() => {
  const p = process.env.OPENTHOMAS_PORT ?? process.env.THOMAS_PORT
  return p ? Number.parseInt(p, 10) : 9877
})()
export const DAEMON_HOST = 'localhost'
export const DAEMON_BASE_URL = `http://${DAEMON_HOST}:${DAEMON_PORT}`
