import type { OutboundFrame } from '../agent/frames.ts';
import { type RunMemory, StoredRunMemory } from '../agent-mode/run-memory.ts';
import { isRecord } from '../fiber/narrow.ts';
import { reportSdkError, setReportIdentityProvider, setReportPublishableKey } from '../telemetry/sdk-reporter.ts';
import type { AgentTransport } from '../transport/transport.ts';
import { ApiClient } from './api-client.ts';
import { watchForeground } from './foreground.ts';
import { ClientHealthProbe } from './health.ts';
import type { BlarIdentity } from './identity.ts';
import { PresenceManager } from './presence.ts';
import { type SessionState, BackendSession } from './session.ts';
import { watchSessionChanges } from './session-change.ts';
import { SessionSocket, type SocketState } from './session-socket.ts';
import { createDefaultStorage, type KeyValueStorage, MemoryStorage } from './storage.ts';
import { getTabId } from './tab-id.ts';

export interface BackendTransportOptions {
  publishableKey: string;
  apiBaseUrl: string;
  user: BlarIdentity | null;
  storage?: KeyValueStorage;
  onSocketState?: (state: SocketState) => void;
  onConnecting?: (sessionId: number) => void;
  onSessionChanged?: () => void;
  log?: (message: string) => void;
}

export interface WidgetProof {
  identityToken?: string;
  identitySignature?: string;
}

type FrameListener = (frame: Record<string, unknown>) => void;

export class BackendTransport implements AgentTransport {
  private readonly api: ApiClient;

  private readonly session: BackendSession;

  private readonly runMemory: StoredRunMemory;

  private readonly health = new ClientHealthProbe();

  private readonly presence: PresenceManager;

  private readonly socket: SessionSocket;

  private readonly tabId = getTabId();

  private readonly frameListeners = new Set<FrameListener>();

  private readonly identityListeners = new Set<() => void>();

  private agentListener: ((raw: string) => void) | null = null;

  private lastSeenSeq = 0;

  private connectedKey: string | null = null;

  private stopped = true;

  private refreshing = false;

  private initialUser: BlarIdentity | null;

  private readonly log: (message: string) => void;

  private readonly onConnecting: (sessionId: number) => void;

  private booted: Promise<void> = Promise.resolve();

  constructor(options: BackendTransportOptions) {
    this.initialUser = options.user;
    this.log = options.log ?? (() => undefined);
    this.api = new ApiClient({ apiBaseUrl: options.apiBaseUrl, publishableKey: options.publishableKey });
    const storage = options.storage ?? createDefaultStorage();
    this.log(`storage ${storage instanceof MemoryStorage ? 'memory' : 'async-storage'}`);
    this.session = new BackendSession(this.api, storage);
    setReportPublishableKey(options.publishableKey);
    setReportIdentityProvider(() => ({
      sourceId: this.session.getState().sourceId,
      sessionId: this.session.getState().sessionId,
      userExternalId: this.getIdentity()?.externalId ?? null,
    }));
    this.runMemory = new StoredRunMemory(storage, `blar_agent_run_${options.publishableKey.slice(-8)}`, () => this.session.getState().sessionId);
    this.onConnecting = options.onConnecting ?? (() => undefined);
    watchSessionChanges((listener) => this.session.subscribe(listener), () => options.onSessionChanged?.());
    this.presence = new PresenceManager(
      this.api,
      () => void this.refreshSession(),
      (message) => this.log(message),
    );
    this.socket = new SessionSocket({
      apiBaseUrl: options.apiBaseUrl,
      publishableKey: options.publishableKey,
      tabId: this.tabId,
      getSourceId: () => this.api.getSourceId(),
      getProof: () => this.api.getIdentityProof(),
      refreshProof: () => this.api.refreshIdentityProof(),
      getLastSeenSeq: () => this.lastSeenSeq,
      onMessage: (raw, frame) => this.receive(raw, frame),
      onState: (state) => {
        this.log(`socket ${state}`);
        options.onSocketState?.(state);
      },
      onIdentityRejected: () => void this.session.logout().then(() => this.connect()),
      watchForeground,
    });
  }

  onMessage(listener: (raw: string) => void): void {
    this.agentListener = listener;
  }

  getRunMemory(): RunMemory {
    return this.runMemory;
  }

  onFrame(listener: FrameListener): () => void {
    this.frameListeners.add(listener);
    return () => this.frameListeners.delete(listener);
  }

  onIdentityChange(listener: () => void): () => void {
    this.identityListeners.add(listener);
    return () => this.identityListeners.delete(listener);
  }

  start(): void {
    this.stopped = false;
    this.health.start();
    this.booted = this.boot();
  }

  stop(): void {
    this.stopped = true;
    this.presence.stop();
    this.health.stop();
    this.socket.disconnect();
    this.connectedKey = null;
  }

  async setUser(identity: BlarIdentity): Promise<void> {
    await this.booted;
    await this.session.setUser(identity);
    await this.connect();
    this.identityListeners.forEach((listener) => listener());
  }

  async logout(): Promise<void> {
    await this.booted;
    await this.session.logout();
    await this.connect();
    this.identityListeners.forEach((listener) => listener());
  }

  isConnected(): boolean {
    return this.socket.isOpen();
  }

  async refreshSession(): Promise<void> {
    if (this.stopped || this.refreshing) {
      return;
    }
    this.refreshing = true;
    try {
      const previous = this.session.getState().sessionId;
      const state = await this.session.refresh();
      this.log(`refreshed session=${state.sessionId} (was ${previous})`);
      if (state.sessionId !== null && state.sessionId !== previous) {
        await this.connect();
      }
    } catch (error) {
      this.log(`refresh failed: ${error instanceof Error ? error.message : String(error)}`);
      reportSdkError('BackendTransport.refreshSession', error);
    } finally {
      this.refreshing = false;
    }
  }

  async switchSession(sessionId: number): Promise<void> {
    this.session.adoptSession(sessionId);
    await this.connect();
  }

  leaveSession(): void {
    this.session.leaveSession();
    this.socket.disconnect();
    this.connectedKey = null;
  }

  async openNudge(): Promise<number | null> {
    const sessionId = await this.api.openNudge(this.tabId);
    this.log(`nudge open -> session=${sessionId}`);
    return sessionId;
  }

  async dismissNudge(milestoneMessageId: number): Promise<void> {
    await this.api.dismissNudge(milestoneMessageId);
    this.log(`nudge dismissed milestone=${milestoneMessageId}`);
  }

  async snoozeNudge(milestoneMessageId: number): Promise<void> {
    await this.api.snoozeNudge(milestoneMessageId);
    this.log(`nudge snoozed milestone=${milestoneMessageId}`);
  }

  getState(): SessionState {
    return this.session.getState();
  }

  getTabId(): string {
    return this.tabId;
  }

  getIdentity(): BlarIdentity | null {
    return this.api.getIdentity();
  }

  async readWidgetProof(): Promise<WidgetProof | null> {
    const proof = await this.api.refreshIdentityProof();
    if (proof === null) {
      return null;
    }
    return proof.header === 'X-Identity-Token' ? { identityToken: proof.value } : { identitySignature: proof.value };
  }

  noteInteraction(): void {
    this.presence.noteInteraction();
  }

  send(frame: OutboundFrame): void {
    if (frame.type === 'pong') {
      this.socket.send(JSON.stringify({ type: 'pong', client: this.health.take() }));
      return;
    }
    if (frame.type === 'command_ack') {
      this.socket.send(JSON.stringify(frame));
      return;
    }
    if (frame.type === 'agent_cancel') {
      this.log(`-> agent_cancel ${frame.reason}`);
      this.socket.send(JSON.stringify(frame));
      return;
    }
    this.log(`-> ${frame.type === 'sdk_response' ? frame.response_type : frame.type} ${frame.command_id}`);
    if (frame.type === 'sdk_response' && frame.response_type === 'agent_command_response') {
      this.log(`   ${JSON.stringify(frame.data)}`);
    }
    if (frame.type === 'sdk_response' && frame.response_type === 'dom_state_response') {
      this.log(`\n${frame.data.html_snapshot}`);
    }
    this.socket.sendOrCache(frame.command_id, JSON.stringify({ ...frame, document_id: this.tabId }));
  }

  private async boot(): Promise<void> {
    try {
      await Promise.all([this.session.boot(this.initialUser), this.runMemory.load()]);
    } catch (error) {
      this.log(`boot failed: ${error instanceof Error ? error.message : String(error)}`);
      reportSdkError('BackendTransport.boot', error);
      return;
    }
    if (this.stopped) {
      return;
    }
    const state = this.session.getState();
    this.log(`booted source=${state.sourceId} session=${state.sessionId} identified=${state.identified}`);
    this.presence.start();
    await this.connect().catch((error: unknown) => {
      this.log(`connect failed: ${error instanceof Error ? error.message : String(error)}`);
      reportSdkError('BackendTransport.connect', error);
    });
  }

  private async connect(): Promise<void> {
    if (this.stopped) {
      return;
    }
    const sessionId = await this.session.ensureSessionId();
    if (this.stopped) {
      return;
    }
    const sourceId = this.api.getSourceId();
    if (sessionId === null || sourceId === null) {
      return;
    }
    const key = `${sessionId}:${sourceId}`;
    if (key === this.connectedKey && this.socket.isOpen()) {
      return;
    }
    this.connectedKey = key;
    this.lastSeenSeq = 0;
    this.log(`connecting session=${sessionId} source=${sourceId}`);
    this.onConnecting(sessionId);
    this.socket.connect(sessionId);
  }

  private receive(raw: string, frame: Record<string, unknown> | null): void {
    if (frame === null) {
      this.agentListener?.(raw);
      return;
    }
    if (frame.type === 'ping') {
      this.send({ type: 'pong' });
      return;
    }
    this.trackSequence(frame);
    if (typeof frame.event === 'string') {
      this.log(`<- ${frame.event} ${this.describeCommand(frame)}`);
      this.agentListener?.(raw);
      return;
    }
    this.frameListeners.forEach((listener) => listener(frame));
  }

  private describeCommand(frame: Record<string, unknown>): string {
    const data = isRecord(frame.data) ? frame.data : {};
    const action = isRecord(data.action) ? JSON.stringify(data.action) : '';
    const target = isRecord(data.target) && typeof data.target.agent_id === 'string' ? data.target.agent_id : '';
    const risk = typeof data.risk_level === 'string' ? `risk=${data.risk_level}` : '';
    return `${action} ${target} ${risk}`.trim();
  }

  private trackSequence(frame: Record<string, unknown>): void {
    const message = isRecord(frame.message) ? frame.message : null;
    if (frame.type === 'message' && message !== null && typeof message.seq === 'number') {
      this.lastSeenSeq = Math.max(this.lastSeenSeq, message.seq);
    }
    if (frame.type === 'history' && Array.isArray(frame.messages)) {
      for (const entry of frame.messages) {
        if (isRecord(entry) && typeof entry.seq === 'number') {
          this.lastSeenSeq = Math.max(this.lastSeenSeq, entry.seq);
        }
      }
    }
  }
}
