import {
  type AgentCapability,
  extractCapabilities,
  materializeChannelCapabilities,
} from '@parall/agent-core';
import type { ParallClient } from '@parall/sdk';
import type { PlatformConfigResponse } from '@parall/sdk';
import * as fs from 'node:fs';
import * as path from 'node:path';

interface CachedPlatformConfig {
  version: string;
  config: Record<string, unknown>;
  fetchedAt: string;
}

// Channel-capability snapshot for the OTHER consumers of capability state:
// the before_prompt_build hook (fragments into the system prompt — evaluated
// every prompt build, so a refresh reaches the very next turn without any
// restart) and the gateway's getCapabilityKeys (hint routing). Updated by
// applyChannelCapabilitySnapshot alongside every config apply, so the shim
// materialization and the declaration can never diverge within a refresh.
// Process-global BY THE SAME assumption as runtime.ts's agentIdentity:
// hosted agents run one-agent-per-pod, so a single snapshot is correct. A
// future multi-account host would need this keyed per account together with
// that identity global — do not fix one without the other.
let currentCapabilities: AgentCapability[] = [];

export function getChannelCapabilityFragments(): string[] {
  return currentCapabilities.map((c) => c.fragment);
}

export function getChannelCapabilityKeys(): string[] {
  return currentCapabilities.map((c) => c.key);
}

function applyChannelCapabilitySnapshot(
  stateDir: string,
  config: Record<string, unknown>,
  log?: { info: (msg: string) => void; warn: (msg: string) => void; error: (msg: string) => void },
): void {
  const caps = extractCapabilities(config);
  materializeChannelCapabilities(stateDir, caps, log);
  currentCapabilities = caps;
}

interface ConfigManagerOpts {
  client: ParallClient;
  stateDir: string;
  configPath: string;
  credentials: { api_key: string; parall_url: string };
  log?: { info: (msg: string) => void; warn: (msg: string) => void; error: (msg: string) => void };
}

const CACHE_FILENAME = 'parall-platform-config.json';

/** Tool names are no longer registered — all operations go through CLI. */

function cachePath(stateDir: string): string {
  return path.join(stateDir, CACHE_FILENAME);
}

function loadCachedConfig(stateDir: string): CachedPlatformConfig | null {
  try {
    const raw = fs.readFileSync(cachePath(stateDir), 'utf-8');
    return JSON.parse(raw) as CachedPlatformConfig;
  } catch {
    return null;
  }
}

function saveCachedConfig(stateDir: string, config: PlatformConfigResponse): void {
  const cached: CachedPlatformConfig = {
    version: config.version,
    config: config.config,
    fetchedAt: new Date().toISOString(),
  };
  const filePath = cachePath(stateDir);
  const tmpPath = `${filePath}.tmp`;
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
  fs.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), 'utf-8');
  fs.renameSync(tmpPath, filePath);
}

/**
 * Deep-merge platform config into an existing openclaw.json file.
 * Only overwrites `models.providers.parall`, `models.providers["parall-anthropic"]`,
 * and `agents.defaults` sections;
 * all other keys (user customizations, other providers) are preserved.
 */
function applyToOpenClawConfig(
  configPath: string,
  platformConfig: Record<string, unknown>,
  credentials: { api_key: string; parall_url: string },
): void {
  let existing: Record<string, unknown> = {};
  try {
    const raw = fs.readFileSync(configPath, 'utf-8');
    existing = JSON.parse(raw) as Record<string, unknown>;
  } catch {
    // File doesn't exist or is invalid — start fresh
  }

  // Deep-merge models.providers for all Parall-managed providers
  // (preserve existing fields, overlay platform, inject credentials).
  const models = (existing.models ?? {}) as Record<string, unknown>;
  const providers = (models.providers ?? {}) as Record<string, unknown>;
  const platformModels = (platformConfig.models ?? {}) as Record<string, unknown>;
  const platformProviders = (platformModels.providers ?? {}) as Record<string, unknown>;

  // Only forward keys OpenClaw's model schema recognizes — its strict Zod
  // validation rejects unrecognized keys and skips the entire config reload.
  const OPENCLAW_MODEL_KEYS = new Set(['id', 'name', 'contextWindow', 'maxTokens']);

  // Parall-managed providers: overlay when present in the platform payload.
  // parall-anthropic is deleted when absent (rollback safety — stale provider
  // would route to anthropic-messages transport that older servers can't auth).
  // parall is never deleted — it's the core provider; a malformed/empty
  // response should not wipe out the agent's only LLM access.
  const PARALL_MANAGED_PROVIDERS = ['parall', 'parall-anthropic'] as const;
  for (const providerName of PARALL_MANAGED_PROVIDERS) {
    const rawProvider = platformProviders[providerName];
    const platformProvider =
      rawProvider && typeof rawProvider === 'object' && !Array.isArray(rawProvider)
        ? (rawProvider as Record<string, unknown>)
        : null;
    if (!platformProvider) {
      if (providerName !== 'parall') delete providers[providerName];
      continue;
    }

    if (Array.isArray(platformProvider.models)) {
      platformProvider.models = (platformProvider.models as Record<string, unknown>[]).map((m) => {
        const cleaned: Record<string, unknown> = {};
        for (const [k, v] of Object.entries(m)) {
          if (OPENCLAW_MODEL_KEYS.has(k)) {
            cleaned[k] = v;
          }
        }
        return cleaned;
      });
    }

    providers[providerName] = {
      ...((providers[providerName] ?? {}) as Record<string, unknown>),
      ...platformProvider,
      apiKey: credentials.api_key,
    };
  }

  models.providers = providers;
  existing.models = models;

  // Strip keys OpenClaw doesn't recognize from agents.defaults — platform-only
  // keys like thinking_effort are consumed by agent-core's PlatformConfigManager.
  // See: OpenClaw agents.defaults config schema.
  const OPENCLAW_AGENTS_DEFAULTS_KEYS = new Set(['model', 'compaction', 'memorySearch']);
  // `model` is platform-sourced (delivered only on the catalog-gated Parall
  // route) — it must NOT be carried over from the existing file, otherwise a
  // stale `parall/...` model survives a switch to runtime_auth (the server then
  // omits agents.defaults entirely) and the runtime keeps using the Parall
  // provider. compaction / memorySearch are operator-tunable, so preserve those
  // across applies; model is re-sourced from the platform overlay below or
  // dropped when the platform sends none.
  const OPENCLAW_PRESERVE_KEYS = new Set(['compaction', 'memorySearch']);

  // Unconditionally sanitize existing defaults to self-heal already-poisoned
  // openclaw.json files (e.g. mode=self agents that were poisoned while in
  // platform mode).
  const agents = (existing.agents ?? {}) as Record<string, unknown>;
  const existingDefaults = (agents.defaults ?? {}) as Record<string, unknown>;
  const cleanedExisting: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(existingDefaults)) {
    if (OPENCLAW_PRESERVE_KEYS.has(k)) {
      cleanedExisting[k] = v;
    }
  }

  // Overlay platform defaults (filtered) when present.
  const platformAgents = (platformConfig.agents ?? {}) as Record<string, unknown>;
  const rawDefaults = platformAgents.defaults;
  if (
    rawDefaults !== undefined &&
    rawDefaults !== null &&
    typeof rawDefaults === 'object' &&
    !Array.isArray(rawDefaults)
  ) {
    const raw = rawDefaults as Record<string, unknown>;
    for (const [k, v] of Object.entries(raw)) {
      if (OPENCLAW_AGENTS_DEFAULTS_KEYS.has(k)) {
        cleanedExisting[k] = v;
      }
    }
  }

  // Bidirectional model rewrite for parall-anthropic. Gate on the fresh
  // platform payload so rollback self-heals without manual intervention.
  if (typeof cleanedExisting.model === 'string') {
    const model = cleanedExisting.model as string;
    if (platformProviders['parall-anthropic']) {
      const fwd = model.match(/^parall\/(anthropic\/.+)$/);
      if (fwd) cleanedExisting.model = `parall-anthropic/${fwd[1]}`;
    } else {
      const rev = model.match(/^parall-anthropic\/(anthropic\/.+)$/);
      if (rev) cleanedExisting.model = `parall/${rev[1]}`;
    }
  }

  agents.defaults = cleanedExisting;
  existing.agents = agents;

  // No plugin tools to allow — all operations go through CLI.

  // Atomic write
  const tmpPath = `${configPath}.tmp`;
  fs.mkdirSync(path.dirname(configPath), { recursive: true });
  fs.writeFileSync(tmpPath, JSON.stringify(existing, null, 2), 'utf-8');
  fs.renameSync(tmpPath, configPath);
}

/**
 * Fetch platform config from the server, cache it (LKG), and apply to openclaw.json.
 * Degrades gracefully: uses cached config on fetch failure, continues if neither is available.
 */
export async function fetchAndApplyPlatformConfig(opts: ConfigManagerOpts): Promise<void> {
  const { client, stateDir, configPath, credentials, log } = opts;

  // 1. Load cached config (LKG)
  const cached = loadCachedConfig(stateDir);

  // 2. Fetch from server (with version for 304)
  let fresh: PlatformConfigResponse | null = null;
  try {
    fresh = await client.getPlatformConfig(cached?.version);
  } catch (err) {
    // Fetch failed — fall through to use cache
    if (cached) {
      log?.warn(
        `platform config fetch failed, using cached version ${cached.version}: ${String(err)}`,
      );
      applyToOpenClawConfig(configPath, cached.config, credentials);
      applyChannelCapabilitySnapshot(stateDir, cached.config, log);
      return;
    }
    // No cache and fetch fails — degrade gracefully
    log?.error(`platform config fetch failed and no cache available: ${String(err)}`);
    return;
  }

  // 3. 304 — config unchanged
  if (fresh === null) {
    log?.info('platform config unchanged (304)');
    if (cached) {
      applyToOpenClawConfig(configPath, cached.config, credentials);
      applyChannelCapabilitySnapshot(stateDir, cached.config, log);
    }
    return;
  }

  // 4. Validate schema compatibility before accepting
  const SUPPORTED_SCHEMA_VERSION = 1;
  if (fresh.schema_version !== undefined && fresh.schema_version > SUPPORTED_SCHEMA_VERSION) {
    log?.error(
      `platform config schema_version ${fresh.schema_version} is newer than supported (${SUPPORTED_SCHEMA_VERSION}), keeping current config`,
    );
    if (cached) {
      applyToOpenClawConfig(configPath, cached.config, credentials);
      applyChannelCapabilitySnapshot(stateDir, cached.config, log);
    }
    return;
  }

  // 5. Newer config received — save cache and apply
  log?.info(`platform config updated to version ${fresh.version}`);
  saveCachedConfig(stateDir, fresh);
  applyChannelCapabilitySnapshot(stateDir, fresh.config, log);
  applyToOpenClawConfig(configPath, fresh.config, credentials);
}
