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

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[];
  runtimeInfo: RuntimeInfo | null;
  storedTotal: number | null;
  learningRuleCount: number;
  snapshotRepo?: SnapshotRepositoryPort;
}

export function useScanSnapshotPublisher({
  autoScanRunning,
  reviewStatus,
  captureStatus,
  selectedSourceName,
  autoScanStats,
  scanSummary,
  snapshot,
  latestInventoryGrid,
  automationLog,
  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),
      runtimeInfo,
      storedTotal,
      learningRuleCount,
      updatedAt: new Date().toISOString(),
    }).catch(() => undefined);
  }, [
    autoScanRunning,
    reviewStatus,
    captureStatus,
    selectedSourceName,
    autoScanStats,
    scanSummary,
    snapshot,
    latestInventoryGrid,
    automationLog,
    runtimeInfo,
    storedTotal,
    learningRuleCount,
    snapshotRepo,
  ]);
}
