import type { AppSnapshot, Artifact, Character, ScanEvent } from "../types/domain";
import { createDemoArtifacts, createDemoCharacters, createDemoScanEvents } from "./demoData";
import { recommendArtifacts, suggestBuilds } from "./scoring";
import { getPresets } from "./demoData";

export interface ScannerEnvironment {
  borderlessWindowed: boolean;
  language: "en" | "unknown";
  resolution: string;
  hdrWarning: boolean;
}

export interface ScannerAdapter {
  checkEnvironment(): Promise<ScannerEnvironment>;
  scanCharacters(): Promise<{ characters: Character[]; events: ScanEvent[] }>;
  scanArtifacts(): Promise<{ artifacts: Artifact[]; events: ScanEvent[] }>;
}

export class MockScannerAdapter implements ScannerAdapter {
  async checkEnvironment(): Promise<ScannerEnvironment> {
    return {
      borderlessWindowed: true,
      language: "en",
      resolution: "2560x1440",
      hdrWarning: false,
    };
  }

  async scanCharacters() {
    await delay(180);
    return {
      characters: createDemoCharacters(),
      events: createDemoScanEvents().filter((event) => event.type === "character"),
    };
  }

  async scanArtifacts() {
    await delay(260);
    return {
      artifacts: createDemoArtifacts(),
      events: createDemoScanEvents().filter((event) => event.type === "artifact"),
    };
  }
}

export async function runAccountScan(adapter: ScannerAdapter = new MockScannerAdapter()): Promise<AppSnapshot> {
  const environment = await adapter.checkEnvironment();
  const characterPass = await adapter.scanCharacters();
  const artifactPass = await adapter.scanArtifacts();
  const presets = getPresets();
  const recommendations = recommendArtifacts(artifactPass.artifacts, characterPass.characters, presets);
  const builds = suggestBuilds(artifactPass.artifacts, characterPass.characters, presets);

  return {
    artifacts: artifactPass.artifacts,
    characters: characterPass.characters,
    recommendations,
    builds,
    scanEvents: [
      {
        id: "environment-live",
        type: "environment",
        label: "Environment check",
        detail: `${environment.borderlessWindowed ? "Borderless ready" : "Borderless required"} · ${environment.resolution} · ${environment.language.toUpperCase()}`,
        confidence: environment.hdrWarning ? 0.78 : 0.94,
      },
      ...characterPass.events,
      ...artifactPass.events,
      {
        id: "complete-live",
        type: "complete",
        label: "Account snapshot ready",
        detail: "Local recommendation engine updated with the latest scan.",
        confidence: 0.95,
      },
    ],
  };
}

function delay(ms: number) {
  return new Promise((resolve) => window.setTimeout(resolve, ms));
}
