#!/usr/bin/env node

import * as os from 'node:os';
import {
  AGENT_SECRETS_WAIT_MS,
  classifyStartupFailure,
  capabilityBinDir,
  childLogger,
  clearAllProviderCreds,
  configureHttpKeepAlive,
  createLogger,
  createOtelLogger,
  createAgentSecretsManager,
  createConfigRefresh,
  createPlatformConfigManager,
  deriveModelIsPin,
  identityFromMe,
  initAgentTelemetry,
  llmSource,
  resolveServiceVersion,
  materializeChannelCapabilities,
  ParallAgentGateway,
  parseDispatchDeadlineMs,
  parseForkDeadlineMs,
  parseProviderConfig,
  parseShutdownDeadlineMs,
  resolveRuntimeContextWindow,
  resolveRuntimeMaxTokens,
  resolveRuntimeModel,
  traceContextHeaders,
  newRuntimeInstanceId,
} from '@parall/agent-core';
import { ApiError, ParallClient, ParallWs } from '@parall/sdk';
import {
  buildClaudeRuntimeKey,
  contextFilePathForSession,
  dispatchContextDirPath,
  resolveClaudeAgentConfig,
  resolveWsUrl,
  sessionStateFilePathForRuntime,
  stepIdFilePathForSession,
} from './config.js';
import { commandEnvSupported, createCommandEnv } from './command-env.js';
import { ClaudeCodeAdapter } from './dispatch.js';
import { ClaudeSessionManager } from './session-manager.js';
import { ensureClaudeWorkspace, writeClaudeSystemPrompt } from './workspace.js';

const log = createLogger('claude-agent');
let activeLog = log;

async function getAgentMeWithLegacyFallback(client: ParallClient, orgId: string) {
  try {
    return await client.getAgentMe(orgId);
  } catch (err) {
    if (!(err instanceof ApiError && err.status === 404)) {
      throw err;
    }
    const user = await client.getMe();
    return { ...user, agent_profile: null, public_profile: null };
  }
}

type AgentMe = Awaited<ReturnType<typeof getAgentMeWithLegacyFallback>>;

function resolveProviderEnv(): string {
  const pc = parseProviderConfig(process.env);
  const source = llmSource(pc);
  if (!pc) return source;
  clearAllProviderCreds(process.env);
  if (source === 'parall') {
    process.env.ANTHROPIC_AUTH_TOKEN = process.env.PRLL_API_KEY;
    process.env.ANTHROPIC_BASE_URL = `${process.env.PRLL_API_URL}/api/llm`;
    process.env.PRLL_CLAUDE_ALLOW_API_KEY = '1';
  } else if (source === 'custom') {
    if (pc.anthropic_auth_token) {
      process.env.ANTHROPIC_AUTH_TOKEN = pc.anthropic_auth_token;
      process.env.PRLL_CLAUDE_ALLOW_API_KEY = '1';
    }
    if (pc.anthropic_base_url) process.env.ANTHROPIC_BASE_URL = pc.anthropic_base_url;
  }
  return source;
}

async function main() {
  // Before any fetch: long-lived HTTP connections for every bridge→api call.
  configureHttpKeepAlive();
  const serviceVersion = resolveServiceVersion(import.meta.url);
  const telemetry = await initAgentTelemetry('parall-claude-agent', 'claude-code', {
    apiUrl: process.env.PRLL_API_URL,
    apiKey: process.env.PRLL_API_KEY,
    serviceVersion,
  });
  activeLog = createOtelLogger('agent', 'claude-agent');
  try {
    const activeLLMSource = resolveProviderEnv();
    const config = resolveClaudeAgentConfig(process.env);

    if (config.allowApiKey && (process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN)) {
      // Surface the billing path: default is OAuth (Claude.ai subscription); this
      // branch means the operator opted into Anthropic API pay-per-use, and the
      // whole point of the strip default is that "silent" is the bad state.
      activeLog.warn(
        'PRLL_CLAUDE_ALLOW_API_KEY=1 — ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN will reach the Claude CLI; billing routes through Anthropic API pay-per-use instead of Claude.ai OAuth.',
      );
    }

    const client = new ParallClient({
      baseUrl: config.apiUrl,
      token: config.apiKey,
      swimlaneName: config.swimlaneName,
      getRequestHeaders: traceContextHeaders,
    });

    const me = await getAgentMeWithLegacyFallback(client, config.orgId);
    const agentUserId = me.id;
    const agentLog = childLogger(activeLog, agentUserId);
    activeLog = agentLog;
    // Shared by the initial workspace write and the config-refresh rewrite of
    // .parall/system-prompt.md — both need identity + capability fragments.
    // Mutable on purpose: refreshPlatformConfig refetches it (see
    // identityFromMe) so profile edits reach the next activation.
    let agentIdentity = identityFromMe(me);
    let lastIdentitySnapshot = JSON.stringify(agentIdentity);
    // Last successful /agents/me profile — deriveModelIsPin's legacy fallback
    // (old servers omit model_is_pin) must not flip a pinned model to floor
    // just because one refresh round-trip failed.
    let lastKnownAgentProfile = me.agent_profile;
    const runtimeKey = config.runtimeKey || buildClaudeRuntimeKey(agentUserId);
    const sessionStateFilePath = sessionStateFilePathForRuntime(config.stateDir, runtimeKey);
    const sessionManager = new ClaudeSessionManager(runtimeKey, sessionStateFilePath, agentLog);

    const resolvedWsUrl = resolveWsUrl(config.apiUrl, config.wsUrl, config.swimlaneName);
    // This process's runtime instance: rides the WS ticket and every claim so
    // the server owns turns by process identity instead of a lease clock
    // (agent-dispatch-idempotency-design.md#instance-ownership).
    const instanceId = newRuntimeInstanceId();
    const ws = new ParallWs({
      getTicket: () => client.getWsTicket({ instance_id: instanceId }),
      wsUrl: resolvedWsUrl,
    });

    const configMgr = createPlatformConfigManager({
      client,
      stateDir: config.stateDir,
      runtimeType: 'claude-code',
      log: agentLog,
    });
    const platformDefaults = await configMgr.fetch();
    // Channel capabilities: ONE call materializes the local artifacts (the
    // lark-cli auth shim under capabilityBinDir) and yields the system-prompt
    // fragments, so declaration and shim can never diverge within a refresh.
    // No freshness gate — a stale (LKG-cached) declaration fail-closes at the
    // mint endpoint, which re-evaluates the grant on every token request.
    const applyChannelCapabilities = () => {
      const caps = configMgr.capabilities();
      materializeChannelCapabilities(config.stateDir, caps, agentLog);
      return caps.map((c) => c.fragment);
    };
    // Assemble the workspace AFTER the first config fetch so system-prompt.md
    // carries the capability declarations from boot (not just from the first
    // heat-update).
    const bootCapabilityFragments = applyChannelCapabilities();
    let lastCapabilityFragments = bootCapabilityFragments.join('\n\n');
    ensureClaudeWorkspace(config.workspaceDir, agentLog, agentIdentity, bootCapabilityFragments);
    // Model precedence: operator PIN (override) > env > server FLOOR. The server
    // now says which it is via model_is_pin (deriveModelIsPin presence-gates the
    // dual-read: old servers omit it → fall back to model_management). A PIN beats
    // an explicit env override; a FLOOR loses to env. effort is delivered by the
    // server only when pinned, so we no longer gate it on a local flag.
    const platformModelOverride = deriveModelIsPin(platformDefaults, me.agent_profile);
    const resolvedModel = resolveRuntimeModel(
      platformModelOverride,
      platformDefaults.model,
      config.model,
    );
    const resolvedContextWindow = resolveRuntimeContextWindow(
      resolvedModel,
      platformDefaults,
      activeLLMSource,
    );
    const resolvedMaxTokens = resolveRuntimeMaxTokens(
      resolvedModel,
      platformDefaults,
      activeLLMSource,
    );
    const resolvedEffort =
      platformDefaults.thinkingEffort ??
      (process.env.CLAUDE_CODE_EFFORT_LEVEL?.trim() || undefined);
    if (platformDefaults.model)
      agentLog.info(
        `platform config: model=${platformDefaults.model} → resolved=${resolvedModel ?? 'cli-default'} (${platformModelOverride ? 'pin/override' : 'floor'})`,
      );
    if (platformDefaults.thinkingEffort)
      agentLog.info(`platform config: thinking_effort=${platformDefaults.thinkingEffort}`);
    if (resolvedContextWindow)
      agentLog.info(`platform config: context_window=${resolvedContextWindow}`);
    if (resolvedMaxTokens) agentLog.info(`platform config: max_tokens=${resolvedMaxTokens}`);

    // Agent secrets: fetched with the agent's own key and exported to its Bash
    // commands through CLAUDE_ENV_FILE. A rewrite reaches the next command, so
    // a set is "applied" as soon as the file is written.
    const commandEnv = commandEnvSupported()
      ? createCommandEnv({
          agentId: agentUserId,
          operatorEnvFile: process.env.CLAUDE_ENV_FILE?.trim() || undefined,
          log: agentLog,
        })
      : undefined;
    const secrets = commandEnv
      ? createAgentSecretsManager({
          fetch: () => client.getMyAgentSecrets(config.orgId),
          ack: (version) => client.ackMyAgentSecrets(config.orgId, version),
          apply: ({ version, env }) => {
            commandEnv.write(env);
            secrets?.markApplied(version);
          },
          log: agentLog,
        })
      : undefined;
    // Bounded: the first command of the first turn should already have them,
    // but an unreachable endpoint must not hold boot.
    await Promise.race([
      secrets?.refresh(),
      new Promise((resolve) => setTimeout(resolve, AGENT_SECRETS_WAIT_MS)),
    ]);

    const adapter = new ClaudeCodeAdapter({
      claudeBin: config.claudeBin,
      claudeHome: config.claudeHome,
      workspaceDir: config.workspaceDir,
      model: resolvedModel,
      contextWindow: resolvedContextWindow,
      maxTokens: resolvedMaxTokens,
      permissionMode: config.permissionMode,
      allowedTools: config.allowedTools,
      disallowedTools: config.disallowedTools,
      additionalDirs: config.additionalDirs,
      appendSystemPrompt: config.appendSystemPrompt,
      allowApiKey: config.allowApiKey,
      sessionManager,
      // Static Parall credentials. The long-lived subprocess must authenticate
      // against Parall's API across many dispatches, so these cannot come from
      // a per-dispatch DispatchContext.
      apiUrl: config.apiUrl,
      apiKey: config.apiKey,
      orgId: config.orgId,
      contextFilePathForSession: (sessionKey) =>
        contextFilePathForSession(config.stateDir, sessionKey),
      stepIdFilePathForSession: (sessionKey) =>
        stepIdFilePathForSession(config.stateDir, sessionKey),
      contextDirPath: dispatchContextDirPath(config.stateDir),
      // Constant PATH prepend; the directory's content (the lark-cli shim)
      // tracks capability grants, so add/remove reaches live subprocesses.
      capabilityBinDir: capabilityBinDir(config.stateDir),
      commandEnvFile: commandEnv?.loaderPath,
    });
    if (resolvedEffort) {
      adapter.updateConfig({ effort: resolvedEffort });
    }

    // The platform half of a config refresh; configRefresh below adds the
    // secrets half and is what onConfigUpdate + onSessionReady call.
    // /agents/me is only consumed as deriveModelIsPin's legacy fallback when
    // the server omits model_is_pin (old server) — skip that round trip
    // otherwise.
    const refreshPlatformConfig = async () => {
      const updated = await configMgr.fetch();
      // Unconditional /agents/me refetch: identity (title / public
      // description / private instructions) rides the same
      // agent_config.update nudge as model config. Failure degrades to the
      // last-known-good identity, mirroring configMgr.fetch()'s cache
      // fallback, so a transient error never rejects this callback. No
      // profile → deriveModelIsPin treats the delivered model as a floor
      // (safe default).
      let refreshedMe: AgentMe | undefined;
      try {
        refreshedMe = await getAgentMeWithLegacyFallback(client, config.orgId);
      } catch (err) {
        agentLog.warn(
          `platform config refresh: /agents/me refetch failed (keeping last-known identity): ${String(err)}`,
        );
      }
      if (refreshedMe) {
        agentIdentity = identityFromMe(refreshedMe);
        lastKnownAgentProfile = refreshedMe.agent_profile;
      }
      const isPin = deriveModelIsPin(updated, lastKnownAgentProfile);
      const localEffort = process.env.CLAUDE_CODE_EFFORT_LEVEL?.trim() || null;
      const model = resolveRuntimeModel(isPin, updated.model, config.model) ?? null;
      adapter.updateConfig({
        model,
        contextWindow: resolveRuntimeContextWindow(model, updated, activeLLMSource) ?? null,
        maxTokens: resolveRuntimeMaxTokens(model, updated, activeLLMSource) ?? null,
        effort: updated.thinkingEffort ?? localEffort,
      });
      // Channel capabilities heat-update with the config: re-materialize the
      // shim and rewrite the standing system prompt on EVERY refresh. The
      // rewrite is unconditional on purpose — it is self-healing: the prompt
      // file lives in the agent-writable workspace, so a subprocess or its
      // tools can delete or tamper with it, and rewriting each refresh/reconnect
      // restores the authoritative copy (do NOT gate this on a fragment change).
      // Revocation keeps the constant pointer in place (no deny stub, no local
      // token cache): the mint endpoint's 403 IS the revocation, nothing local
      // to purge. The shim swap reaches even live long-lived subprocesses
      // immediately (PATH re-resolves per command), but the system prompt was
      // loaded at spawn — so a CHANGED declaration also marks live processes for
      // a lazy --resume respawn, the same mechanism model changes use.
      const fragments = applyChannelCapabilities();
      const joinedFragments = fragments.join('\n\n');
      // Refresh path: TOLERATE a prompt-write failure (boot is fatal instead) —
      // a transient failure must not break the whole config heat-update. But do
      // NOT advance the snapshot / restart unless the write actually LANDED:
      // otherwise a later successful retry sees "no change" and never restarts
      // the long-lived Claude subprocess, stranding it on the stale prompt. The
      // rewrite is self-healing; leaving the snapshot put makes the next refresh
      // retry and, on success, restart.
      let promptWritten = true;
      try {
        writeClaudeSystemPrompt(config.workspaceDir, agentIdentity, fragments);
      } catch (err) {
        promptWritten = false;
        agentLog.warn(`system prompt refresh write failed (retrying next refresh): ${String(err)}`);
      }
      // Identity changes ride the same lazy-respawn mechanism as capability
      // fragments: the live child loaded its prompt at spawn, so a changed
      // identity marks it for an out-of-turn --resume respawn and the next
      // activation runs with the new prompt.
      const identitySnapshot = JSON.stringify(agentIdentity);
      if (
        promptWritten &&
        (joinedFragments !== lastCapabilityFragments || identitySnapshot !== lastIdentitySnapshot)
      ) {
        lastCapabilityFragments = joinedFragments;
        lastIdentitySnapshot = identitySnapshot;
        adapter.requestProcessRestart();
      }
    };
    // Both halves of a refresh, and what a claimed turn waits for: the env
    // file rewritten to the version its claim named (and the prompt that
    // lists a new name respawned with it) before the turn starts.
    const configRefresh = createConfigRefresh({
      secrets,
      refreshPlatform: refreshPlatformConfig,
      log: agentLog,
    });

    const gateway = new ParallAgentGateway({
      accountId: agentUserId,
      client,
      ws,
      instanceId,
      connectionLabel: resolvedWsUrl,
      config: {
        parall_url: config.apiUrl,
        api_key: config.apiKey,
        org_id: config.orgId,
      },
      agentUserId,
      runtimeType: 'claude-code',
      runtimeVersion: serviceVersion,
      // Declared only where this bridge actually delivers them.
      runtimeFeatures: secrets ? ['agent_secrets'] : [],
      runtimeKey,
      runtimeRef: {
        hostname: os.hostname(),
        pid: process.pid,
        workspace_dir: config.workspaceDir,
        claude_home: config.claudeHome,
      },
      dispatchAdapter: adapter,
      log: agentLog,
      // Live capability view for hint routing: the channel reply hint points
      // at the vendor CLI only while the grant is active (config manager
      // re-fetches on agent_config.update, so revocation reaches the very
      // next dispatch's hint).
      getCapabilityKeys: () => configMgr.capabilities().map((c) => c.key),
      shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
      forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
      dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),
      contextFilePathForSession: (sessionKey) =>
        contextFilePathForSession(config.stateDir, sessionKey),
      stepIdFilePathForSession: (sessionKey) =>
        stepIdFilePathForSession(config.stateDir, sessionKey),
      dispatchContextDir: dispatchContextDirPath(config.stateDir),
      onConfigUpdate: () => configRefresh.refresh(),
      onSessionReady: () => configRefresh.refresh(),
      alignSecrets: (version) => configRefresh.alignSecrets(version),
      // Long-lived `claude` subprocesses outlive a single dispatch, so the
      // gateway's shuttingDown flag alone does not tear them down. Piggyback on
      // onBeforeDisconnect to close stdin and SIGTERM any survivors after
      // in-flight drains finish.
      onBeforeDisconnect: async () => {
        secrets?.stop();
        try {
          await adapter.shutdown();
        } finally {
          // After the children are gone: nothing sources the files any more.
          commandEnv?.dispose();
        }
      },
      onNewSession: async () => {
        sessionManager.clearMainSession();
        adapter.resetProcesses();
      },
      onSessionStale: () => {
        sessionManager.clearMainSession();
        adapter.resetProcesses();
      },
    });

    const abortController = new AbortController();
    const abort = () => abortController.abort();
    process.on('SIGINT', abort);
    process.on('SIGTERM', abort);

    try {
      agentLog.info(`starting self-hosted Claude runtime for ${me.display_name} (${agentUserId})`);
      await gateway.run(abortController.signal);
    } finally {
      process.off('SIGINT', abort);
      process.off('SIGTERM', abort);
    }
  } finally {
    await telemetry.shutdown();
  }
}

main().catch((err) => {
  // A credential the server rejects during bootstrap is the same terminal
  // failure the gateway reports as auth-invalid: exit with the re-mint code
  // so the daemon mints a fresh launch credential instead of restarting
  // this process with the same dead key.
  const { exitCode, authRejection } = classifyStartupFailure(err);
  if (authRejection) {
    activeLog.error(
      `AUTH-INVALID at startup status=${authRejection.status}` +
        `${authRejection.code ? ` code=${authRejection.code}` : ''} — ` +
        `the server rejected this runtime's credential (${authRejection.message}); ` +
        `exiting with code ${exitCode} so the supervisor can re-mint the launch credential.`,
    );
  } else {
    activeLog.error(`fatal: ${String(err)}`);
  }
  process.exitCode = exitCode;
});
