import { prisma } from "@/lib/prisma";
import type { PlatformCandidate, HostingCandidate } from "./platform-signatures";

interface UpsertArgs {
  trackedSiteId: string;
  platform: PlatformCandidate;
  hosting?: HostingCandidate;
}

const DAY_MS = 24 * 60 * 60 * 1000;

function confidenceLabel(weight: number): "high" | "medium" | "low" {
  if (weight >= 80) return "high";
  if (weight >= 60) return "medium";
  return "low";
}

// Returns a comparable rank for stored string labels so the guard
// can decide whether a new detection should overwrite an existing one.
function confidenceRank(label: string | null): number {
  if (label === "high") return 3;
  if (label === "medium") return 2;
  if (label === "low") return 1;
  return 0;
}

export async function upsertDetectedPlatform({ trackedSiteId, platform, hosting }: UpsertArgs): Promise<void> {
  const site = await prisma.trackedSite.findUnique({
    where: { id: trackedSiteId },
    select: {
      sitePlatform: true,
      sitePlatformConfidence: true,
      sitePlatformDetectedAt: true,
    },
  });

  if (!site) return;

  const now = new Date();
  const newLabel = confidenceLabel(platform.confidence);
  const existingRank = confidenceRank(site.sitePlatformConfidence);
  const newRank = confidenceRank(newLabel);

  // 24h rate limit: skip if recently written and new confidence is not strictly higher
  if (site.sitePlatformDetectedAt) {
    const age = now.getTime() - site.sitePlatformDetectedAt.getTime();
    if (age < DAY_MS && newRank <= existingRank) return;
  }

  // Confidence rank guard: never overwrite a higher-confidence detection
  if (site.sitePlatform && newRank < existingRank) return;

  await prisma.trackedSite.update({
    where: { id: trackedSiteId },
    data: {
      sitePlatform: platform.name,
      sitePlatformVersion: platform.version ?? null,
      sitePlatformConfidence: newLabel,
      sitePlatformCategory: platform.category,
      sitePlatformDetectedAt: now,
      ...(hosting ? { siteHosting: hosting.name, siteHostingDetectedAt: now } : {}),
    },
  });
}
