/**
 * AI Strategist Analysis Schema
 * ──────────────────────────────
 * Structured analysis object that drives both:
 *   1. Live interactive artifact (React panel with charts/cards)
 *   2. Narrative executive report (written output)
 *
 * The schema is source-agnostic — the analysis job populates it
 * from whatever sources are available (GSC, GA4, audits, manual, web research).
 */

// ─── Core Analysis Object ───────────────────────────────────────────────────

export interface Analysis {
  id: string;
  brandId: string;
  type: AnalysisType;
  status: "queued" | "running" | "completed" | "failed";
  createdAt: string;
  completedAt?: string;

  // Branding
  branding: AnalysisBranding;

  // Job input
  prompt?: string;
  manualCaveats?: string[];
  uploadedNotes?: string[];

  // Header
  title: string;
  subtitle: string;
  summary: string;

  // Time context
  period: { start: string; end: string; label: string };
  comparisonPeriod?: { start: string; end: string; label: string };

  // Data sources used
  sources: AnalysisSource[];

  // Sections (ordered)
  kpis: KpiItem[];
  findings: Finding[];
  charts: ChartSpec[];
  tables: TableSpec[];
  timeline: TimelineEvent[];
  predictions: Prediction[];
  recommendations: AnalysisRecommendation[];
  caveats: Caveat[];

  // External research evidence
  research?: ResearchContext;

  // Narrative output
  narrative?: {
    executiveSummary: string;
    detailedReport: string;
    methodology: string;
  };

  // Error info
  errorMessage?: string;
}

// ─── Branding ───────────────────────────────────────────────────────────────

export interface AnalysisBranding {
  appBrand: "meSEO";
  clientName: string;
  clientDomain: string;
  clientLogoUrl: string | null;
  clientLogoSource: "brand_profile" | "website_intake" | "manual" | "none";
  reportDate: string;
  artifactTheme: "default" | "dark" | "branded";
  artifactHeaderMeta: {
    generatedBy: string;
    analysisType: string;
    periodLabel: string;
  };
}

// ─── Analysis Types ─────────────────────────────────────────────────────────

export type AnalysisType =
  | "seasonal_performance"   // YoY / seasonal anomaly analysis
  | "traffic_deep_dive"      // Traffic source breakdown
  | "conversion_analysis"    // Conversion funnel analysis
  | "technical_health"       // Technical audit deep dive
  | "competitor_gap"         // Competitor analysis
  | "custom";                // Free-form analysis

// ─── Sources ────────────────────────────────────────────────────────────────

export interface AnalysisSource {
  id: string;
  type: "gsc" | "ga4" | "technical_audit" | "performance_audit" | "manual" | "document" | "web_research" | "site_tag" | "ai_attribution";
  label: string;
  status: "available" | "missing" | "partial" | "stale";
  recordCount?: number;
  dateRange?: { start: string; end: string };
}

// ─── KPIs ───────────────────────────────────────────────────────────────────

export interface KpiItem {
  label: string;
  value: string;
  unit?: string;
  /** Raw numeric value for comparison math in downstream consumers */
  rawValue?: number;
  /** Value from the comparison period for inline display */
  previousValue?: string;
  /** Period-over-period change */
  change?: { value: number; direction: "up" | "down" | "flat"; label: string };
  /** Year-over-year change (separate from period-over-period) */
  yoyChange?: { value: number; direction: "up" | "down" | "flat"; label: string };
  status: "good" | "warning" | "critical" | "neutral";
  source: string;
  /** Trend interpretation from the time-series of this metric within the period */
  trend?: "improving" | "declining" | "stable" | "volatile";
  /** Analyst commentary explaining the "why" behind the numbers */
  commentary?: string;
  /** Category for grouping KPIs in the UI */
  category?: "search" | "engagement" | "conversion" | "technical";
  /** Data coverage: how many days of the requested range actually have data */
  dataCoverage?: { daysWithData: number; totalDays: number; firstDataDate?: string };
}

// ─── Findings ───────────────────────────────────────────────────────────────

export interface Finding {
  id: string;
  type: "insight" | "anomaly" | "trend" | "risk" | "opportunity";
  severity: "critical" | "high" | "medium" | "low" | "info";
  title: string;
  description: string;
  evidence: string;        // What data backs this
  impact?: string;         // Business impact explanation
  /** Categorical impact level for sorting and prioritisation */
  impactLevel?: "high" | "medium" | "low";
  /** Broad category of the finding */
  category?: "performance" | "technical" | "content" | "competitive" | "opportunity";
  /** Short recommended action (full rec exists in recommendations list with matching ID) */
  recommendedAction?: string;
  affectedMetric?: string;
  affectedPeriod?: string;
  citations?: CitationRef[];  // References to research evidence
}

// ─── Charts ─────────────────────────────────────────────────────────────────

export interface ChartSpec {
  id: string;
  type: "line" | "bar" | "composed" | "area" | "pie";
  title: string;
  subtitle?: string;
  xAxis: { label: string; key: string };
  yAxes: Array<{ label: string; key: string; color: string; type?: "line" | "bar" | "area" }>;
  data: Array<Record<string, string | number>>;
  annotations?: Array<{ x: string; label: string; color: string }>;
  source: string;
}

// ─── Tables ─────────────────────────────────────────────────────────────────

export interface TableSpec {
  id: string;
  title: string;
  columns: Array<{ key: string; label: string; align?: "left" | "center" | "right"; format?: "number" | "percent" | "currency" | "text" }>;
  rows: Array<Record<string, string | number>>;
  source: string;
  sortBy?: string;
  sortDir?: "asc" | "desc";
}

// ─── Timeline Events ────────────────────────────────────────────────────────

export interface TimelineEvent {
  date: string;
  type: "event" | "anomaly" | "change" | "launch" | "external";
  title: string;
  description: string;
  impact?: "positive" | "negative" | "neutral";
  source: string;
}

// ─── Predictions ────────────────────────────────────────────────────────────

export interface Prediction {
  metric: string;
  current: number;
  predicted: number;
  confidence: "high" | "medium" | "low";
  timeframe: string;
  basis: string; // What the prediction is based on
  caveat?: string;
  /** Categorical type for grouping predictions (traffic trajectory, seasonal, risk) */
  predictionType?: "trajectory" | "seasonal" | "risk" | "opportunity";
  /** Human-readable outlook label (e.g. "On track", "At risk", "Strong growth") */
  outlook?: string;
}

// ─── Recommendations ────────────────────────────────────────────────────────

export interface AnalysisRecommendation {
  priority: "critical" | "high" | "medium" | "low";
  /** Alternative P1/P2/P3 label used by some consumers; derived from priority */
  priorityLabel?: "P1" | "P2" | "P3" | "P4";
  title: string;
  description: string;
  expectedImpact: string;
  effort: "low" | "medium" | "high";
  /** Human-readable effort label for display */
  effortLabel?: "quick-win" | "moderate" | "major";
  /** Broad category matching finding categories */
  category?: "performance" | "technical" | "content" | "competitive" | "opportunity";
  /** Ordered list of concrete action steps */
  steps?: string[];
  relatedFinding?: string; // Finding ID
  citations?: CitationRef[];  // References to research evidence
}

// ─── Caveats ────────────────────────────────────────────────────────────────

export interface Caveat {
  type: "data_gap" | "methodology" | "external_factor" | "confidence" | "staleness";
  title: string;
  description: string;
  severity: "info" | "warning" | "critical";
  affectedSections: string[];
}

// ─── Research Evidence ─────────────────────────────────────────────────────

/** Full research context attached to an analysis */
export interface ResearchContext {
  /** Research queries executed */
  queries: ResearchQuery[];
  /** All evidence items gathered */
  evidence: ResearchEvidence[];
  /** When the research was performed */
  performedAt: string;
  /** How many queries succeeded vs failed */
  stats: { queriesRun: number; queriesSucceeded: number; evidenceGathered: number };
}

/** A single research query and its results */
export interface ResearchQuery {
  id: string;
  query: string;
  purpose: string;            // Why this query was run (e.g. "seasonal SEO trends")
  resultCount: number;
  status: "completed" | "failed" | "no_results";
  errorMessage?: string;
}

/** A single piece of external evidence */
export interface ResearchEvidence {
  id: string;
  queryId: string;            // Which query produced this
  sourceType: "web_search" | "web_page" | "uploaded_document" | "manual_note";
  sourceName: string;         // Site name or document name
  sourceUrl: string | null;   // URL if web-sourced
  title: string;
  snippet: string;            // Key extracted text
  fullContent?: string;       // Longer extracted content if page was fetched
  dateCaptured: string;       // ISO timestamp
  relevance: "high" | "medium" | "low";
  citationLabel: string;      // Short label for inline refs (e.g. "[1]", "[Search Engine Journal]")
  sectionMapping: string[];   // Which analysis sections this supports (e.g. ["findings", "recommendations"])
}

/** Inline citation reference used in findings/recommendations */
export interface CitationRef {
  evidenceId: string;         // Points to ResearchEvidence.id
  label: string;              // Display label (e.g. "[1]" or "[Search Engine Land]")
  url: string | null;
}
