/**
 * Social Proof Signal Deriver
 * -----------------------------
 * Composes existing audit data to extract social proof signals.
 * Makes NO new API calls -- entirely derived from data already collected.
 *
 * Internal module -- vendor names permitted in code; forbidden in user-facing output.
 */

export interface SocialProofResult {
  totalReviewCount: number;
  avgRating: number | null;
  reviewSchemaPresent: boolean;
  aggregateRatingSchemaPresent: boolean;
  hasVisibleReviewWidget: boolean;
}

export function deriveSocialProof(existingAuditContext: {
  eeatAudit?: { signals?: Array<{ dimension: string; score: number }> } | null;
  liveVisualAnnotations?: {
    perPageAnnotations?: Array<{
      annotations?: Array<{ id: string }>;
    }>;
  } | null;
  schemaOpportunityForecast?: {
    prioritySchemaTypes?: Array<{ schemaType: string; present: boolean }>;
  } | null;
}): SocialProofResult {
  // Derive aggregateRating schema presence from schema forecast data
  const schemaTypes = existingAuditContext.schemaOpportunityForecast?.prioritySchemaTypes ?? [];
  const aggregateRatingSchemaPresent = schemaTypes.some(
    (s) => /aggregaterating|review/i.test(s.schemaType) && s.present,
  );
  const reviewSchemaPresent = schemaTypes.some(
    (s) => /review/i.test(s.schemaType) && s.present,
  );

  // Derive visible review widget from visual annotations
  const hasVisibleReviewWidget = (existingAuditContext.liveVisualAnnotations?.perPageAnnotations ?? []).some(
    (page) => (page.annotations ?? []).some((ann) => ann.id === "no-social-proof"),
  )
    ? false  // annotation "no-social-proof" means it is ABSENT
    : (existingAuditContext.liveVisualAnnotations?.perPageAnnotations?.length ?? 0) > 0;

  // E-E-A-T review signal as a proxy for review volume
  const reviewSignal = existingAuditContext.eeatAudit?.signals?.find(
    (s) => /review|social|proof|rating/i.test(s.dimension),
  );
  const totalReviewCount = reviewSignal ? Math.round(reviewSignal.score * 10) : 0;
  const avgRating = reviewSignal && reviewSignal.score > 0 ? Math.min(5, 3 + reviewSignal.score / 50) : null;

  return {
    totalReviewCount,
    avgRating,
    reviewSchemaPresent,
    aggregateRatingSchemaPresent,
    hasVisibleReviewWidget,
  };
}
