import type { IndustryContext } from "../synthesizers/industry-classifier";
import type { IndustryBenchmarkComparison } from "../types";
import { getBenchmarkForIndustry } from "../data/industry-benchmarks";

const INDUSTRY_DISPLAY_NAMES: Record<string, string> = {
  "local-services": "Local Services",
  "healthcare-medical": "Healthcare (Medical)",
  "healthcare-dental": "Dental Practice",
  "b2b-saas": "B2B SaaS",
  "ecommerce": "E-Commerce",
  "professional-services": "Professional Services",
  "finance": "Financial Services",
  "legal": "Legal Services",
  "real-estate": "Real Estate",
  "nonprofit": "Nonprofit",
  "hospitality": "Hospitality",
  "higher-ed": "Higher Education",
  "other": "General Business",
};

function computePercentile(brandValue: number, industryP25: number, industryP75: number): number {
  if (brandValue >= industryP75) return Math.min(95, 75 + ((brandValue - industryP75) / (industryP75 - industryP25 || 1)) * 20);
  if (brandValue <= industryP25) return Math.max(5, 25 - ((industryP25 - brandValue) / (industryP75 - industryP25 || 1)) * 20);
  return 25 + ((brandValue - industryP25) / (industryP75 - industryP25)) * 50;
}

function toStanding(percentile: number): "top-25" | "top-50" | "bottom-50" | "bottom-25" {
  if (percentile >= 75) return "top-25";
  if (percentile >= 50) return "top-50";
  if (percentile >= 25) return "bottom-50";
  return "bottom-25";
}

interface DimensionInput {
  name: string;
  brandValue: number;
  industryAverage: number;
  industryP25: number;
  industryP75: number;
}

function buildDimension(input: DimensionInput) {
  const raw = computePercentile(input.brandValue, input.industryP25, input.industryP75);
  const brandPercentile = Math.round(Math.max(5, Math.min(95, raw)));
  return {
    name: input.name,
    brandValue: input.brandValue,
    industryAverage: input.industryAverage,
    industryP25: input.industryP25,
    industryP75: input.industryP75,
    brandPercentile,
    brandStanding: toStanding(brandPercentile),
    gapToAverage: input.brandValue - input.industryAverage,
    gapToTopQuartile: input.brandValue - input.industryP75,
  };
}

export function aggregateIndustryBenchmarkComparison(
  industryContext: IndustryContext,
  backlinkProfile: { referringDomains: number | null; totalBacklinks: number | null; domainRank: number | null } | null | undefined,
  serpAnalysis: { aiOverviewPresence: Array<{ hasAiOverview: boolean; brandMentioned: boolean }> } | null | undefined,
  pageCount: number,
  schemaCoveragePercent: number,
): IndustryBenchmarkComparison | null {
  const bm = getBenchmarkForIndustry(industryContext.industry);
  const dimensions: ReturnType<typeof buildDimension>[] = [];

  if (backlinkProfile?.referringDomains != null) {
    dimensions.push(buildDimension({
      name: "Referring Domains",
      brandValue: backlinkProfile.referringDomains,
      industryAverage: bm.avgReferringDomains,
      industryP25: bm.p25DomainAuthority,
      industryP75: bm.p75DomainAuthority,
    }));
  }

  if (backlinkProfile?.totalBacklinks != null) {
    dimensions.push(buildDimension({
      name: "Total Backlinks",
      brandValue: backlinkProfile.totalBacklinks,
      industryAverage: bm.avgBacklinks,
      industryP25: Math.round(bm.avgBacklinks * 0.3),
      industryP75: Math.round(bm.avgBacklinks * 1.8),
    }));
  }

  const aiEntries = serpAnalysis?.aiOverviewPresence ?? [];
  if (aiEntries.length >= 3) {
    const totalWithAiOverview = aiEntries.filter((e) => e.hasAiOverview).length;
    const brandMentionedCount = aiEntries.filter((e) => e.hasAiOverview && e.brandMentioned).length;
    const citationRate = totalWithAiOverview > 0 ? brandMentionedCount / totalWithAiOverview : 0;
    dimensions.push(buildDimension({
      name: "AI Visibility Rate",
      brandValue: Math.round(citationRate * 100),
      industryAverage: Math.round(bm.avgAiOverviewCitationRate * 100),
      industryP25: Math.round(bm.avgAiOverviewCitationRate * 100 * 0.25),
      industryP75: Math.round(bm.avgAiOverviewCitationRate * 100 * 1.8),
    }));
  }

  dimensions.push(buildDimension({
    name: "Indexed Page Depth",
    brandValue: pageCount,
    industryAverage: bm.avgPageCount,
    industryP25: Math.round(bm.avgPageCount * 0.35),
    industryP75: Math.round(bm.avgPageCount * 2.2),
  }));

  const schemaCoverageP75 = Math.min(100, Math.round(bm.avgSchemaCoverage * 100 * 1.6));
  dimensions.push(buildDimension({
    name: "Schema Coverage",
    brandValue: schemaCoveragePercent,
    industryAverage: Math.round(bm.avgSchemaCoverage * 100),
    industryP25: Math.round(bm.avgSchemaCoverage * 100 * 0.5),
    industryP75: schemaCoverageP75,
  }));

  if (dimensions.length < 2) return null;

  const overallPercentile = Math.round(
    dimensions.reduce((sum, d) => sum + d.brandPercentile, 0) / dimensions.length,
  );

  return {
    industry: industryContext.industry,
    industryDisplayName: INDUSTRY_DISPLAY_NAMES[industryContext.industry] ?? "General Business",
    dimensions,
    overallPercentile,
    benchmarkConfidence: "low" as const,
  };
}
