import type { PluginRuntime } from 'openclaw/plugin-sdk';
import type { ChannelPlugin } from 'openclaw/plugin-sdk/core';

/** Extract ChannelGatewayAdapter from ChannelPlugin (removed from public SDK exports in 2026.3.24). */
type ChannelGatewayAdapter<T = unknown> = NonNullable<ChannelPlugin<T>['gateway']>;
import {
  ParallAgentGateway,
  capabilityBinDir,
  dispatchLaneContextDir,
  parseShutdownDeadlineMs,
  parseForkDeadlineMs,
  parseDispatchDeadlineMs,
  identityFromMe,
  initAgentTelemetry,
  createOtelLogger,
  type DispatchAdapter,
  type ParallEvent,
  type RuntimeEvent,
  type TurnOutcomeEvent,
} from '@parall/agent-core';
import {
  appendPreparedLocalAttachmentRefs,
  ensureLocalAttachmentGitExclude,
  pinLocalAttachmentPaths,
} from '@parall/agent-core/internal/attachment-input';
import { ApiError, ParallClient, ParallWs } from '@parall/sdk';
import type { ParallChannelConfig } from './types.js';
import * as crypto from 'node:crypto';
import * as os from 'node:os';
import * as path from 'node:path';
import { resolveParallAccount } from './accounts.js';
import {
  getParallRuntime,
  removeParallAccountState,
  setAgentIdentity,
  setAgentSessionBinding,
  setDispatchGroupKey,
  setParallAccountState,
} from './runtime.js';
import { buildOrchestratorSessionKey } from './session.js';
import type { ResolvedParallAccount } from './types.js';
import { fetchAndApplyPlatformConfig, getChannelCapabilityKeys } from './config-manager.js';
import { startWikiHelper } from './wiki-helper.js';
import { SessionManager } from './oc-session.js';
import {
  cleanupForkSession,
  clearSessionState,
  forkOrchestratorSession,
  resolveSessionId,
  resolveTranscriptFile,
} from './fork.js';

/**
 * Per-session dispatch context file (PRLL_CONTEXT_FILE contract) — same
 * encoding as the claude/codex bridges: base64url(sessionKey) under the
 * state dir's dispatch-context/.
 */
function sessionContextFilePath(stateDir: string, sessionKey: string): string {
  const fileName = Buffer.from(sessionKey).toString('base64url');
  return path.join(stateDir, 'dispatch-context', `${fileName}.json`);
}

function resolveWsUrl(account: ResolvedParallAccount): string {
  if (account.config.ws_url) return account.config.ws_url;
  const base = account.config.parall_url.replace(/\/$/, '');
  const wsBase = base.replace(/^http/, 'ws');
  return `${wsBase}/ws`;
}

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 };
  }
}

// hooks.ts rebuilds the prompt from the process-global identity on EVERY
// prompt build, so a refreshed identity (via the shared identityFromMe)
// reaches the very next turn without any restart.

function buildInboundCtx(
  core: PluginRuntime,
  accountId: string,
  event: ParallEvent,
  sessionKey: string,
  bodyForAgent: string,
  earlierEvents: ParallEvent[] = [],
): Record<string, unknown> {
  const inboundHistory = earlierEvents.length > 0 ? buildInboundHistory(earlierEvents) : undefined;
  // The server frame is the whole text of the event (agent-core renders
  // nothing); OpenClaw's inbound context gets it as the body.
  const body = event.frame ?? '';
  return core.channel.reply.finalizeInboundContext({
    Body: body,
    BodyForAgent: bodyForAgent,
    RawBody: body,
    CommandBody: body,
    // Attachment metadata is now in event.attachments (structured), not mediaFields
    ...(inboundHistory?.length ? { InboundHistory: inboundHistory } : {}),
    From: `parall:${event.senderId}`,
    To: `parall:orchestrator`,
    SessionKey: sessionKey,
    AccountId: accountId,
    ChatType: event.targetType ?? 'unknown',
    SenderName: event.senderId,
    SenderId: event.senderId,
    Provider: 'parall' as const,
    Surface: 'parall' as const,
    MessageSid: event.messageId,
    Timestamp: Date.now(),
    CommandAuthorized: true,
    OriginatingChannel: 'parall' as const,
    OriginatingTo: `parall:orchestrator`,
  });
}

function buildInboundHistory(events: ParallEvent[]): Array<{ sender: string; body: string }> {
  // Each earlier event is its own server frame (message ids, thread,
  // attachments and hints are already inside it).
  return events.map((event) => ({ sender: event.senderId, body: event.frame ?? '' }));
}

const OC_AUTH_TEXT = /unauthorized|401|403|invalid api key|authentication/i;
const OC_CONTEXT_TEXT = /context (window|length)|prompt is too long|request too large|413/i;
const OC_API_TEXT = /overloaded|429|rate limit|5\d\d|bad gateway|service unavailable|timeout/i;

/**
 * Best-effort classification of an OpenClaw dispatch failure
 * (agent-turn-outcome-design.md §4.3). OpenClaw surfaces LLM errors as
 * opaque thrown Errors, so this is message sniffing only: auth / context /
 * api families when recognizable, runtime_crash otherwise. usage_limit is
 * deliberately never produced here — OpenClaw's own 429 loop-ceiling shares
 * the wording, and a wrong deferral is costlier than a plain retry.
 */
function classifyOpenClawFailure(err: unknown): TurnOutcomeEvent {
  const message = err instanceof Error ? err.message : String(err);
  let outcome: TurnOutcomeEvent['outcome'] = 'runtime_crash';
  if (OC_AUTH_TEXT.test(message)) outcome = 'auth';
  else if (OC_CONTEXT_TEXT.test(message)) outcome = 'context_overflow';
  else if (OC_API_TEXT.test(message)) outcome = 'api_error';
  return {
    type: 'turn_outcome',
    outcome,
    ...(message ? { detail: message.slice(0, 500) } : {}),
  };
}

function createRuntimeEventStream() {
  const queue: RuntimeEvent[] = [];
  const waiters: Array<{
    resolve: (value: RuntimeEvent | undefined) => void;
    reject: (reason?: unknown) => void;
  }> = [];
  let done = false;
  let failure: unknown;

  function flush() {
    while (waiters.length > 0) {
      if (failure) {
        waiters.shift()!.reject(failure);
        continue;
      }
      if (queue.length > 0) {
        waiters.shift()!.resolve(queue.shift());
        continue;
      }
      if (done) {
        waiters.shift()!.resolve(undefined);
        continue;
      }
      break;
    }
  }

  return {
    push(event: RuntimeEvent) {
      queue.push(event);
      flush();
    },
    end() {
      done = true;
      flush();
    },
    fail(err: unknown) {
      failure = err;
      while (waiters.length > 0) {
        waiters.shift()!.reject(err);
      }
    },
    async *stream(): AsyncGenerator<RuntimeEvent> {
      while (true) {
        if (queue.length > 0) {
          yield queue.shift()!;
          continue;
        }
        if (failure) throw failure;
        if (done) return;

        const next = await new Promise<RuntimeEvent | undefined>((resolve, reject) => {
          waiters.push({ resolve, reject });
        });
        if (!next) return;
        yield next;
      }
    },
  };
}

async function waitForOpenClawSessionId(
  sessionsDir: string,
  sessionKey: string,
  timeoutMs = 10_000,
): Promise<string | null> {
  const existing = resolveSessionId(sessionsDir, sessionKey);
  if (existing) return existing;

  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    await new Promise((resolve) => setTimeout(resolve, 100));
    const sessionId = resolveSessionId(sessionsDir, sessionKey);
    if (sessionId) return sessionId;
  }
  return null;
}

export function createOpenClawDispatchAdapter(opts: {
  core: PluginRuntime;
  cfg: Record<string, unknown>;
  accountId: string;
  sessionsDir: string;
  workspaceDir: string;
}): DispatchAdapter {
  const activeStreams = new Map<string, ReturnType<typeof createRuntimeEventStream>>();
  let configFallbackWarned = false;

  /**
   * Resolve the config for one dispatch. OpenClaw hot-reloads
   * `agents.defaults.model` / `models.providers` WITHOUT restarting channel
   * plugins, so the `ctx.cfg` snapshot captured at startAccount goes stale the
   * moment the operator switches the agent's model — every run would keep the
   * old model until the whole gateway restarts. `core.config.current()` is the
   * host's live (hot-reload-refreshed) config; fall back to the startup
   * snapshot on hosts that predate the API. The fallback warns once per
   * degradation streak (latch resets on success) — silently dispatching with
   * the stale snapshot would recreate the invisible model-switch mismatch this
   * function exists to fix.
   */
  function resolveDispatchConfig(log?: { warn?: (msg: string) => void }): Record<string, unknown> {
    try {
      const current = opts.core.config?.current?.();
      if (current && typeof current === 'object') {
        configFallbackWarned = false;
        return current as unknown as Record<string, unknown>;
      }
      if (!configFallbackWarned) {
        configFallbackWarned = true;
        log?.warn?.(
          `parall[${opts.accountId}]: config.current() unavailable on this host — dispatching with the startup config snapshot; model switches need a gateway restart until then`,
        );
      }
    } catch (err) {
      if (!configFallbackWarned) {
        configFallbackWarned = true;
        log?.warn?.(
          `parall[${opts.accountId}]: config.current() failed (${String(err)}) — dispatching with the startup config snapshot; model switches need a gateway restart until then`,
        );
      }
    }
    return opts.cfg;
  }

  return {
    // dispatch() maps earlierEvents into native InboundHistory below — the
    // gateway must not also concatenate them into bodyForAgent.
    earlierEventsInPrompt: true,

    abortDispatch(sessionKey: string): void {
      activeStreams.get(sessionKey)?.fail(new Error('dispatch deadline exceeded'));
    },

    async *dispatch({ event, earlierEvents = [], bodyForAgent, sessionKey, context }) {
      let promptBody = bodyForAgent;
      let releasePreparedAttachments = () => {};
      try {
        const prepared = await appendPreparedLocalAttachmentRefs(bodyForAgent, event, context, {
          workspaceDir: opts.workspaceDir,
          log: context.log,
        });
        promptBody = prepared.body;
        releasePreparedAttachments = pinLocalAttachmentPaths(prepared.attachments.images);
      } catch (err) {
        context.log?.warn?.(`failed to prepare local attachments: ${String(err)}`);
      }

      try {
        const stream = createRuntimeEventStream();
        activeStreams.set(sessionKey, stream);
        let reasoningBuffer = '';
        let turnGroupKey = '';

        const run = opts.core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
          ctx: buildInboundCtx(
            opts.core,
            opts.accountId,
            event,
            sessionKey,
            promptBody,
            earlierEvents,
          ),
          cfg: resolveDispatchConfig(context.log),
          dispatcherOptions: {
            deliver: async (payload: { text?: string }) => {
              const replyText = payload.text?.trim();
              if (!replyText) return;
              stream.push({
                type: 'text',
                text: replyText,
                project: false,
                groupKey: turnGroupKey || undefined,
              });
            },
            onReplyStart: () => {
              turnGroupKey = crypto.randomUUID();
              setDispatchGroupKey(sessionKey, turnGroupKey);
            },
          },
          replyOptions: {
            onReasoningStream: (payload: { text?: string }) => {
              reasoningBuffer += payload.text ?? '';
            },
            onReasoningEnd: async () => {
              if (!reasoningBuffer) return;
              stream.push({
                type: 'thinking',
                text: reasoningBuffer,
                groupKey: turnGroupKey || undefined,
              });
              reasoningBuffer = '';
            },
          },
        });

        run
          .then(() => stream.end())
          .catch((err) => {
            // Best-effort LLM-layer classification before the stream throws
            // (agent-turn-outcome-design.md §4.3): the queue drains ahead of
            // the failure, so the gateway records the class even though the
            // turn still fails. OpenClaw swallows provider detail, so
            // usage_limit detection is deliberately NOT attempted here.
            stream.push(classifyOpenClawFailure(err));
            stream.fail(err);
          });
        let sessionId: string | null;
        try {
          sessionId = await Promise.race([
            waitForOpenClawSessionId(opts.sessionsDir, sessionKey),
            run.then(
              () => null as string | null,
              (err) => {
                throw err;
              },
            ),
          ]);
        } catch {
          sessionId = null;
        }
        if (!sessionId) {
          stream.fail(new Error(`OpenClaw did not expose a sessionId for ${sessionKey}`));
        } else {
          yield {
            type: 'runtime_session',
            runtimeSessionId: sessionId,
            runtimeLaneKey: sessionKey,
          };
        }
        yield* stream.stream();
      } finally {
        activeStreams.delete(sessionKey);
        releasePreparedAttachments();
      }
    },

    getBranchPoint(sessionKey: string): string | undefined {
      const transcriptFile = resolveTranscriptFile(opts.sessionsDir, sessionKey);
      if (!transcriptFile) return undefined;
      try {
        const manager = SessionManager.open(transcriptFile);
        return manager.getLeafId() ?? undefined;
      } catch {
        return undefined;
      }
    },

    forkSession({ sessionKey, preDispatchBranchPoint }) {
      const transcriptFile = resolveTranscriptFile(opts.sessionsDir, sessionKey);
      if (!transcriptFile) return null;
      return forkOrchestratorSession({
        orchestratorSessionKey: sessionKey,
        accountId: opts.accountId,
        transcriptFile,
        sessionsDir: opts.sessionsDir,
        branchPointId: preDispatchBranchPoint,
      });
    },

    cleanupFork({ fork }) {
      if (typeof fork.sessionFile !== 'string') return;
      cleanupForkSession({
        sessionFile: fork.sessionFile,
        sessionKey: fork.sessionKey,
        sessionsDir: opts.sessionsDir,
      });
    },
  };
}

export const parallGateway: ChannelGatewayAdapter<ResolvedParallAccount> = {
  startAccount: async (ctx) => {
    const account = resolveParallAccount({ cfg: ctx.cfg, accountId: ctx.accountId });
    if (!account.enabled) return;
    if (!account.configured)
      throw new Error('Parall account is not configured: parall_url/api_key/org_id required');

    const { config } = account;
    const core = getParallRuntime();
    const log = ctx.log;

    const client = new ParallClient({
      baseUrl: config.parall_url,
      token: config.api_key,
      swimlaneName: process.env.PRLL_SWIMLANE_NAME,
    });

    const me = await getAgentMeWithLegacyFallback(client, config.org_id);
    const agentUserId = me.id;
    setAgentIdentity(identityFromMe(me));
    log?.info(`parall[${ctx.accountId}]: authenticated as ${me.display_name} (${agentUserId})`);

    const telemetry = await initAgentTelemetry('parall-openclaw-agent', 'openclaw');
    const otelLog = createOtelLogger('agent', 'openclaw-agent');
    try {
      const stateDir =
        process.env.OPENCLAW_STATE_DIR || path.join(process.env.HOME || '/data', '.openclaw');
      const openclawConfigPath = path.join(stateDir, 'openclaw.json');

      // Channel-capability shims resolve ahead of any globally-installed CLI
      // of the same name. The plugin runs INSIDE the openclaw process, whose
      // env every exec-tool child inherits — one idempotent prepend here
      // covers the agent's shell commands for the process lifetime (the
      // DIRECTORY is constant; its content tracks capability grants).
      const shimDir = capabilityBinDir(stateDir);
      const currentPath = process.env.PATH ?? '';
      if (!currentPath.split(path.delimiter).includes(shimDir)) {
        process.env.PATH = currentPath ? `${shimDir}${path.delimiter}${currentPath}` : shimDir;
      }

      const configManagerOpts = {
        client,
        stateDir,
        configPath: openclawConfigPath,
        credentials: { api_key: config.api_key, parall_url: config.parall_url },
        log: otelLog,
      };

      try {
        await fetchAndApplyPlatformConfig(configManagerOpts);
      } catch (err) {
        otelLog.warn(`parall[${ctx.accountId}]: platform config fetch failed: ${String(err)}`);
      }

      let stopWikiHelper: (() => void) | null = null;
      let wikiMountRoot: string | undefined;
      try {
        const wikiHelper = await startWikiHelper({
          accountId: ctx.accountId,
          parallUrl: config.parall_url,
          apiKey: config.api_key,
          orgId: config.org_id,
          agentId: agentUserId,
          stateDir,
          log: otelLog,
        });
        wikiMountRoot = wikiHelper.mountRoot;
        stopWikiHelper = wikiHelper.stop;
      } catch (err) {
        otelLog.warn(`parall[${ctx.accountId}]: wiki helper startup failed: ${String(err)}`);
      }

      const wsUrl = resolveWsUrl(account);
      const ws = new ParallWs({
        getTicket: () => client.getWsTicket(),
        wsUrl,
      });
      const orchestratorKey = buildOrchestratorSessionKey(ctx.accountId);
      const sessionsDir = path.join(stateDir, 'agents', 'main', 'sessions');
      const workspaceDir = process.cwd();
      ensureLocalAttachmentGitExclude(workspaceDir);
      const dispatchAdapter = createOpenClawDispatchAdapter({
        core,
        cfg: ctx.cfg,
        accountId: ctx.accountId,
        sessionsDir,
        workspaceDir,
      });

      const gateway = new ParallAgentGateway({
        accountId: ctx.accountId,
        client,
        ws,
        connectionLabel: wsUrl,
        config: {
          parall_url: config.parall_url,
          api_key: config.api_key,
          org_id: config.org_id,
        },
        agentUserId,
        runtimeType: 'openclaw',
        runtimeKey: orchestratorKey,
        runtimeRef: { hostname: os.hostname(), pid: process.pid },
        dispatchAdapter,
        // Opts openclaw into the dispatch ledger (claim/fold/complete +
        // idempotent reply effects) — the same shared-gateway machinery
        // claude/codex ride; openclaw stays buffer-only (no mid-turn steer),
        // which the ledger does not require. Replies already flow through
        // @parall/cli, which reads PRLL_CONTEXT_DIR (injected in hooks.ts)
        // to bind dispatch_lane + reply effect keys.
        // Design: docs/engineering-design/dispatch-convergence-design.md §7 (S2).
        dispatchContextDir: dispatchLaneContextDir(stateDir),
        // Per-session context file (PRLL_CONTEXT_FILE contract) — the CLI's
        // TYPED dispatch binding (parall tasks update → task_update effect)
        // reads lane/event/task fields from this file, not the lane dir.
        contextFilePathForSession: (sessionKey: string) =>
          sessionContextFilePath(stateDir, sessionKey),
        log: otelLog,
        // Live capability view for hint routing: the channel reply hint
        // points at the vendor CLI only while the grant is active.
        getCapabilityKeys: getChannelCapabilityKeys,
        shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
        forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
        dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),
        onConfigUpdate: async () => {
          // Identity rides the same agent_config.update nudge: refresh the
          // process-global identity so the next prompt build (hooks.ts
          // before_prompt_build) carries the new title / public description /
          // instructions. The finally keeps it running even when the platform
          // config refresh throws (their failure domains are independent);
          // identity failure keeps the last-known-good value.
          try {
            await fetchAndApplyPlatformConfig(configManagerOpts);
          } finally {
            try {
              setAgentIdentity(
                identityFromMe(await getAgentMeWithLegacyFallback(client, config.org_id)),
              );
            } catch (err) {
              log?.warn(
                `parall[${ctx.accountId}]: /agents/me refetch failed (keeping last-known identity): ${String(err)}`,
              );
            }
          }
        },
        onSessionReady: async ({ activeSessionId }) => {
          setParallAccountState(ctx.accountId, {
            client,
            apiUrl: config.parall_url,
            apiKey: config.api_key,
            orgId: config.org_id,
            agentUserId,
            activeSessionId,
            sessionBindings: new Map<string, string>(),
            sessionsDir,
            runtimeRef: { hostname: os.hostname(), pid: process.pid },
            wikiMountRoot,
            ws,
            orchestratorSessionKey: orchestratorKey,
            dispatchContextDir: dispatchLaneContextDir(stateDir),
            contextFilePathForSession: (sessionKey: string) =>
              sessionContextFilePath(stateDir, sessionKey),
            // Lease-renewal bridge: openclaw tool calls flow through hooks,
            // not the RuntimeEvent stream, so hook activity must renew the
            // ledger lanes or a long exec outlives the lease (STALE_LANE).
            touchRuntimeActivity: (sessionKey: string) => gateway.touchRuntimeActivity(sessionKey),
          });
        },
        onSessionBinding: async ({ sessionKey, agentSessionId }) => {
          setAgentSessionBinding(ctx.accountId, sessionKey, agentSessionId);
        },
        onBeforeDisconnect: async () => {
          stopWikiHelper?.();
          removeParallAccountState(ctx.accountId);
        },
        onNewSession: () => {
          clearSessionState(sessionsDir, orchestratorKey);
        },
        onSessionStale: () => {
          clearSessionState(sessionsDir, orchestratorKey);
        },
      });

      try {
        await gateway.run(ctx.abortSignal);
      } finally {
        if (!ctx.abortSignal.aborted) {
          stopWikiHelper?.();
          removeParallAccountState(ctx.accountId);
        }
      }
    } finally {
      await telemetry.shutdown();
    }
  },
};
