import type { ParsedArtifactCandidate } from "./artifactOcrParser";
import type { CaptureResult } from "../types/global";

const assistantUiNeedles = [
  "artifacts scannen",
  "scanner diagnose",
  "review queue",
  "build-optionen",
  "build options",
  "input-broker",
  "auto-scan",
  "manuell mitlesen",
  "einzelnes artifact lesen",
];

export function captureRejectionReason(capture: CaptureResult | null, parsed: ParsedArtifactCandidate | null) {
  if (!capture) return "Keine Capture-Daten vorhanden.";
  const sourceRejection = captureSourceRejectionReason(capture);
  if (sourceRejection) return sourceRejection;
  if (!parsed) return "Artifact konnte aus dem Capture nicht geparst werden.";
  if (parsed.name === "Unknown artifact") return "Artifact-Name ist unbekannt.";
  if (parsed.slot === "Unknown slot") return "Artifact-Slot ist unbekannt.";
  if (parsed.setName === "Unknown set") return "Artifact-Set ist unbekannt.";
  if (parsed.mainStat === "Unknown main stat" || parsed.mainValue === "?") return "Main Stat ist unvollstaendig.";
  return "";
}

export function captureSourceRejectionReason(capture: CaptureResult | null) {
  if (!capture) return "Keine Capture-Daten vorhanden.";
  if (capture.captureTarget === "primary-screen") {
    return "Capture stammt nur vom Primary Screen statt vom Genshin-Client.";
  }
  if (looksLikeAssistantUi(capture)) return "Capture enthaelt UI-Text der App statt eines Genshin-Artifacts.";
  return "";
}

export function shouldPersistParsedArtifact(parsed: ParsedArtifactCandidate, needsReview: boolean) {
  if (parsed.name === "Unknown artifact") return false;
  if (parsed.slot === "Unknown slot") return false;
  if (parsed.setName === "Unknown set") return false;
  if (parsed.mainStat === "Unknown main stat") return false;
  if (parsed.mainValue === "?") return false;
  if (parsed.substats.length === 0) return false;
  if (!needsReview && parsed.confidence < 68) return false;
  if (needsReview && parsed.confidence < 60) return false;
  return true;
}

function looksLikeAssistantUi(capture: CaptureResult) {
  const joined = (capture.ocr ?? [])
    .map((entry) => entry.text ?? "")
    .join("\n")
    .toLowerCase();
  return assistantUiNeedles.some((needle) => joined.includes(needle));
}
