import { useEffect } from "react"
import type {
  AppConfig,
  ChatLaunchState,
  ChatMessage,
  GatewayHealth,
  GatewayStatus,
  LogEntry,
  RuntimeCloudStatus,
  RuntimeStatus,
  RuntimeTelemetryStatus,
  SystemSummary,
  WorkspaceSummary
} from "@qjclaw/shared-types"
import { isMockDesktopApi, smokeEnabled } from "../../lib/desktop-api"
import type { SmokeStreamSnapshot } from "./types"

type ViewMode = "chat" | "experts" | "plugins" | "settings" | "knowledge"

export interface SmokeUiSnapshot {
  shellReady: boolean
  bindingRequired: boolean
  isBound: boolean
  showStartupOverlay: boolean
  showBindEntry: boolean
  saving: boolean
  chatLaunchState: ChatLaunchState
  startupPhase: WorkspaceSummary["startupPhase"]
  currentProjectId?: string
  sessionScopeProjectId?: string
  homeIntentSuggestionVisible?: boolean
  homeIntentSuggestionProjectId?: string
  homeIntentSuggestionProjectName?: string
  pendingHomeIntentPrompt?: string
}

export interface UseSmokeSnapshotDeps {
  viewMode: ViewMode
  gatewayStatus: GatewayStatus | null
  gatewayHealth: GatewayHealth | null
  runtimeStatus: RuntimeStatus | null
  runtimeCloudStatus: RuntimeCloudStatus | null
  runtimeTelemetry: RuntimeTelemetryStatus | null
  config: AppConfig | null
  systemSummary: SystemSummary | null
  sessions: WorkspaceSummary["sessions"]
  messages: ChatMessage[]
  messagesBySession: Record<string, ChatMessage[]>
  activeSessionId: string
  expertProjectIds: string[]
  workspaceSummary: WorkspaceSummary | null
  streamSmoke: SmokeStreamSnapshot | null
  ui: SmokeUiSnapshot
  experts: {
    standaloneIds: string[]
    homeShortcutIds: string[]
    standalonePromptAvailableIds: string[]
  }
}

function normalizeSmokeStreamSnapshot(streamSmoke: SmokeStreamSnapshot | null): SmokeStreamSnapshot | null {
  if (!streamSmoke) {
    return null
  }

  if (["completed", "fallback", "error"].includes(streamSmoke.phase)) {
    return streamSmoke
  }

  if (streamSmoke.completedEventCount > 0 && Boolean(streamSmoke.finalContent)) {
    return {
      ...streamSmoke,
      phase: "completed"
    }
  }

  return streamSmoke
}

export function useSmokeSnapshot(deps: UseSmokeSnapshotDeps) {
  useEffect(() => {
    if (!smokeEnabled) {
      delete window.__QJC_SMOKE__
      return
    }

    window.__QJC_SMOKE__ = {
      usingMockApi: isMockDesktopApi,
      viewMode: deps.viewMode,
      gatewayStatus: deps.gatewayStatus,
      gatewayHealth: deps.gatewayHealth,
      runtimeStatus: deps.runtimeStatus,
      runtimeCloudStatus: deps.runtimeCloudStatus,
      runtimeTelemetry: deps.runtimeTelemetry,
      config: deps.config,
      authSession: null,
      profile: null,
      credits: null,
      skills: deps.workspaceSummary?.skills ?? [],
      modelConfig: deps.config?.expertModelConfig ?? null,
      systemSummary: deps.systemSummary,
      sessions: deps.sessions,
      messages: deps.messages,
      messagesBySession: deps.messagesBySession,
      logs: [] as LogEntry[],
      activeSessionId: deps.activeSessionId,
      expertProjectIds: deps.expertProjectIds,
      workspaceSummary: deps.workspaceSummary,
      streamSmoke: normalizeSmokeStreamSnapshot(deps.streamSmoke),
      ui: deps.ui,
      experts: deps.experts
    }
  }, [deps])
}
