/**
 * AI Engine Personality Analysis — Aggregation Service
 * ──────────────────────────────────────────────────────
 * Always returns populated data (static profiles). For 1st-party audits,
 * overlays per-engine behavioral performance from aiAttributionContext.
 *
 * Internal module — engine names are acceptable in user-facing output here
 * because they ARE the product being discussed (see ai-engine-personalities.ts).
 */

import { AI_ENGINE_PROFILES } from "../data/ai-engine-personalities";
import type { AiAttributionContext } from "../types";
import type { AiEnginePersonalityAnalysis, EnginePersonalityCard } from "../types";

// Maps raw aiPlatform strings from attribution data to engineIds
const ENGINE_ALIAS_MAP: Record<string, string> = {
  "chatgpt": "chatgpt",
  "chat.openai.com": "chatgpt",
  "openai": "chatgpt",
  "perplexity": "perplexity",
  "perplexity.ai": "perplexity",
  "claude": "claude",
  "claude.ai": "claude",
  "anthropic": "claude",
  "gemini": "gemini",
  "gemini.google.com": "gemini",
  "google gemini": "gemini",
  "bard": "gemini",
  "copilot": "copilot",
  "bing copilot": "copilot",
  "microsoft copilot": "copilot",
  "bing": "copilot",
  "copilot.microsoft.com": "copilot",
};

function resolveEngineId(raw: string): string | null {
  const lower = raw.toLowerCase().trim();
  return ENGINE_ALIAS_MAP[lower] ?? null;
}

export function aggregateAiEnginePersonalityAnalysis(
  aiAttribution: AiAttributionContext | null,
): AiEnginePersonalityAnalysis {
  // Build per-engine 1st-party overlay from attribution data
  const engineStats = new Map<string, { sessions: number; conversions: number; topLandingPages: Array<{ url: string; aiVisits: number; conversions: number }> }>();

  if (aiAttribution) {
    // Aggregate totals by engine from topEngines
    for (const eng of aiAttribution.topEngines) {
      const id = resolveEngineId(eng.engine);
      if (!id) continue;
      const entry = engineStats.get(id) ?? { sessions: 0, conversions: 0, topLandingPages: [] };
      entry.sessions += eng.count;
      engineStats.set(id, entry);
    }

    // Build top landing pages per engine from topPages (attribute evenly across pages)
    // We don't have per-engine per-page data, so we attach all top pages to the
    // engine that drove the most sessions — a reasonable heuristic given data structure.
    const topEngineId = aiAttribution.topEngines[0]
      ? resolveEngineId(aiAttribution.topEngines[0].engine)
      : null;

    if (topEngineId) {
      const entry = engineStats.get(topEngineId);
      if (entry) {
        entry.topLandingPages = aiAttribution.topPages
          .slice(0, 3)
          .map((p) => ({ url: p.url, aiVisits: p.aiVisits, conversions: p.conversions }));
        engineStats.set(topEngineId, entry);
      }
    }

    // Fill conversions into engine stats using conversion rate from aiAttribution
    const overallRate = aiAttribution.totalAiReferrals > 0
      ? aiAttribution.totalConversions30d / aiAttribution.totalAiReferrals
      : 0;
    for (const [id, entry] of engineStats.entries()) {
      if (entry.conversions === 0 && entry.sessions > 0) {
        entry.conversions = Math.round(entry.sessions * overallRate);
        engineStats.set(id, entry);
      }
    }
  }

  // Find top engine by sessions (for 1st-party callout)
  let topEngineId: string | null = null;
  let topEngineSessionCount = 0;
  for (const [id, stats] of engineStats.entries()) {
    if (stats.sessions > topEngineSessionCount) {
      topEngineSessionCount = stats.sessions;
      topEngineId = id;
    }
  }

  const engines: EnginePersonalityCard[] = AI_ENGINE_PROFILES.map((profile) => {
    const stats = engineStats.get(profile.engineId);
    const conversionRate = stats && stats.sessions > 0
      ? Math.round((stats.conversions / stats.sessions) * 1000) / 10
      : null;

    return {
      engineId: profile.engineId,
      displayName: profile.displayName,
      parentCompany: profile.parentCompany,
      citationStyle: profile.citationStyle,
      preferredContentTypes: profile.preferredContentTypes,
      schemaPriorities: profile.schemaPriorities,
      eAtSensitivity: profile.eAtSensitivity,
      recencyBias: profile.recencyBias,
      optimizationApproach: profile.optimizationApproach,
      firstPartyOverlay: stats
        ? {
            sessions30d: stats.sessions,
            conversions30d: stats.conversions,
            conversionRate,
            topLandingPages: stats.topLandingPages,
          }
        : null,
    };
  });

  return {
    engines,
    topEngineId: aiAttribution ? topEngineId : null,
  };
}
