import { useEffect } from "react";
import { type AppSnapshot } from "../../../types/domain";
import { type AutoScanStats, type ScanSummary } from "../../../lib/scannerSession";
import type { RuntimeInfo } from "../../../types/global";
import type { SnapshotRepositoryPort } from "../../../infrastructure/repositories/rendererBridgeRepositoryTypes";
import type { CaptureResult } from "../../../types/global";
import { validateLookupPackage } from "../../../lib/genshinLookup";
import type { ScanDiagnosticEvent } from "../../../lib/scanDiagnosticsLog";

type InventoryGrid = NonNullable<CaptureResult["inventoryGrid"]>;

interface ScanSnapshotPublisherInput {
  autoScanRunning: boolean;
  reviewStatus: string;
  captureStatus: string;
  selectedSourceName: string | null;
  autoScanStats: AutoScanStats;
  scanSummary: ScanSummary | null;
  snapshot: AppSnapshot;
  latestInventoryGrid: InventoryGrid | null | undefined;
  automationLog: string[];
  diagnosticEvents: ScanDiagnosticEvent[];
  runtimeInfo: RuntimeInfo | null;
  storedTotal: number | null;
  learningRuleCount: number;
  snapshotRepo?: SnapshotRepositoryPort;
}

export function useScanSnapshotPublisher({
  autoScanRunning,
  reviewStatus,
  captureStatus,
  selectedSourceName,
  autoScanStats,
  scanSummary,
  snapshot,
  latestInventoryGrid,
  automationLog,
  diagnosticEvents,
  runtimeInfo,
  storedTotal,
  learningRuleCount,
  snapshotRepo,
}: ScanSnapshotPublisherInput) {
  useEffect(() => {
    void snapshotRepo?.publishScannerStatus({
      running: autoScanRunning,
      reviewStatus,
      captureStatus,
      selectedSource: selectedSourceName,
      stats: autoScanStats,
      summary: scanSummary,
      snapshotArtifacts: snapshot.artifacts.length,
      snapshotCharacters: snapshot.characters.filter((character) => character.owned).length,
      snapshotRecommendations: snapshot.recommendations.length,
      snapshotBuilds: snapshot.builds.length,
      grid: latestInventoryGrid ?? null,
      automationLog: automationLog.slice(-12),
      diagnosticEvents: diagnosticEvents.slice(-8).map((event) => ({
        ...event,
        capture: event.capture
          ? {
              ...event.capture,
              screenshots: event.capture.screenshots
                ? {
                    detail: event.capture.screenshots.detail ? "[detail screenshot available in Diagnose]" : undefined,
                    inventory: event.capture.screenshots.inventory ? "[inventory screenshot available in Diagnose]" : undefined,
                    full: event.capture.screenshots.full ? "[full screenshot omitted]" : undefined,
                  }
                : undefined,
            }
          : undefined,
      })),
      runtimeInfo,
      storedTotal,
      learningRuleCount,
      lookupStatus: validateLookupPackage(),
      ocrEngine: "current",
      entryMode: scanSummary?.mode.includes("auto-entry")
        ? "auto-entry"
        : scanSummary?.mode.includes("direct-inventory")
          ? "direct-inventory"
          : scanSummary?.mode.includes("paimon-menu")
            ? "paimon-menu"
            : "visible-inventory",
      updatedAt: new Date().toISOString(),
    }).catch(() => undefined);
  }, [
    autoScanRunning,
    reviewStatus,
    captureStatus,
    selectedSourceName,
    autoScanStats,
    scanSummary,
    snapshot,
    latestInventoryGrid,
    automationLog,
    diagnosticEvents,
    runtimeInfo,
    storedTotal,
    learningRuleCount,
    snapshotRepo,
  ]);
}
