import prisma from '../lib/prisma.js';

// Type helper to convert Decimal to number
const toNumber = (value: any): number | null => {
  if (value == null) return null;
  if (typeof value === 'number') return value;
  if (value && typeof value.toNumber === 'function') {
    return value.toNumber();
  }
  const num = Number(value);
  return isNaN(num) ? null : num;
};

export interface PropertyScore {
  finalScore: number;
  featuredBoost: number;
  engagementZScore: number;
  recencyScore: number;
  agentBoost: number;
  qualityScore: number;
}

interface PropertyWithRelations {
  id: string;
  featured: boolean;
  featuredUntil: Date | null;
  publishedAt: Date | null;
  viewCount: number;
  clickCount: number;
  favoriteCount: number;
  messageCount: number;
  verified: boolean;
  description: string | null;
  price: number | any | null;
  bedrooms: number | null;
  bathrooms: number | null;
  areaSqft: number | null;
  address: string | null;
  city?: string | null;
  subCity?: string | null;
  propertyType?: string | null;
  listingType?: string | null;
  photos?: Array<{ id: string }>;
  amenities?: Array<{ id: string }>;
  owner?: {
    id: string;
    role: string;
    verified: boolean;
    agentProfile?: {
      verificationStatus: string;
    } | null;
  };
  boostRequests?: Array<{
    id: string;
    status: string;
    plan: {
      days: number;
    };
    createdAt: Date;
  }>;
}

interface EngagementStats {
  viewCount: { mean: number; stdDev: number };
  clickCount: { mean: number; stdDev: number };
  favoriteCount: { mean: number; stdDev: number };
  messageCount: { mean: number; stdDev: number };
}

/**
 * Calculate Z-score: (value - mean) / stdDev
 * Returns 0 if stdDev is 0 (all values are the same)
 */
function calculateZScore(value: number, mean: number, stdDev: number): number {
  if (stdDev === 0) return 0;
  return (value - mean) / stdDev;
}

/**
 * Compute engagement statistics (mean and stdDev) for all properties in a single pass
 * This is O(n) and much more efficient than calculating scores individually
 */
function computeEngagementStats(properties: PropertyWithRelations[]): EngagementStats {
  if (properties.length === 0) {
    return {
      viewCount: { mean: 0, stdDev: 0 },
      clickCount: { mean: 0, stdDev: 0 },
      favoriteCount: { mean: 0, stdDev: 0 },
      messageCount: { mean: 0, stdDev: 0 },
    };
  }

  // First pass: calculate means
  let sumViews = 0;
  let sumClicks = 0;
  let sumFavorites = 0;
  let sumMessages = 0;

  for (const p of properties) {
    sumViews += p.viewCount || 0;
    sumClicks += p.clickCount || 0;
    sumFavorites += p.favoriteCount || 0;
    sumMessages += p.messageCount || 0;
  }

  const meanViews = sumViews / properties.length;
  const meanClicks = sumClicks / properties.length;
  const meanFavorites = sumFavorites / properties.length;
  const meanMessages = sumMessages / properties.length;

  // Second pass: calculate variance
  let varianceViews = 0;
  let varianceClicks = 0;
  let varianceFavorites = 0;
  let varianceMessages = 0;

  for (const p of properties) {
    const views = p.viewCount || 0;
    const clicks = p.clickCount || 0;
    const favorites = p.favoriteCount || 0;
    const messages = p.messageCount || 0;

    varianceViews += Math.pow(views - meanViews, 2);
    varianceClicks += Math.pow(clicks - meanClicks, 2);
    varianceFavorites += Math.pow(favorites - meanFavorites, 2);
    varianceMessages += Math.pow(messages - meanMessages, 2);
  }

  const stdDevViews = Math.sqrt(varianceViews / properties.length);
  const stdDevClicks = Math.sqrt(varianceClicks / properties.length);
  const stdDevFavorites = Math.sqrt(varianceFavorites / properties.length);
  const stdDevMessages = Math.sqrt(varianceMessages / properties.length);

  return {
    viewCount: { mean: meanViews, stdDev: stdDevViews },
    clickCount: { mean: meanClicks, stdDev: stdDevClicks },
    favoriteCount: { mean: meanFavorites, stdDev: stdDevFavorites },
    messageCount: { mean: meanMessages, stdDev: stdDevMessages },
  };
}

/**
 * Calculate featured boost score (0-100)
 * Simple linear scoring - no normalization needed
 */
function calculateFeaturedBoost(property: PropertyWithRelations, now: Date): number {
  if (!property.featured) return 0;

  if (property.featuredUntil && property.featuredUntil <= now) {
    return 0;
  }

  let baseScore = 100;
  let multiplier = 1.0;

  // Check for approved boost request (paid boost)
  const activeBoostRequest = property.boostRequests?.find(
    (br) => br.status === 'APPROVED'
  );

  if (activeBoostRequest) {
    multiplier = 1.5; // Paid boost gets 50% multiplier
    if (property.featuredUntil) {
      const daysRemaining =
        (property.featuredUntil.getTime() - now.getTime()) / (1000 * 60 * 60 * 24);
      if (daysRemaining < 3) {
        multiplier = 1.3;
      }
    }
  } else {
    multiplier = 1.2; // Admin-manual featured gets 20% boost
  }

  // Time decay for featured properties older than 1 week
  if (property.publishedAt) {
    const daysSincePublished =
      (now.getTime() - property.publishedAt.getTime()) / (1000 * 60 * 60 * 24);
    if (daysSincePublished > 7) {
      const weeksOld = Math.floor((daysSincePublished - 7) / 7);
      const decayFactor = Math.max(0.5, 1 - weeksOld * 0.1);
      multiplier *= decayFactor;
    }
  }

  return Math.min(100, baseScore * multiplier);
}

/**
 * Calculate engagement Z-score using normalized metrics
 * Uses Z-score normalization to automatically adjust for dataset size
 */
function calculateEngagementZScore(
  property: PropertyWithRelations,
  stats: EngagementStats
): number {
  const viewZ = calculateZScore(property.viewCount || 0, stats.viewCount.mean, stats.viewCount.stdDev);
  const clickZ = calculateZScore(property.clickCount || 0, stats.clickCount.mean, stats.clickCount.stdDev);
  const favoriteZ = calculateZScore(property.favoriteCount || 0, stats.favoriteCount.mean, stats.favoriteCount.stdDev);
  const messageZ = calculateZScore(property.messageCount || 0, stats.messageCount.mean, stats.messageCount.stdDev);

  // Weighted average of Z-scores
  // Z-scores can be negative, so we normalize to 0-100 range
  // Using sigmoid-like transformation: (z + 3) / 6 * 100, clamped to 0-100
  const normalizeZ = (z: number): number => {
    const normalized = ((z + 3) / 6) * 100;
    return Math.max(0, Math.min(100, normalized));
  };

  const viewScore = normalizeZ(viewZ);
  const clickScore = normalizeZ(clickZ);
  const favoriteScore = normalizeZ(favoriteZ);
  const messageScore = normalizeZ(messageZ);

  // Weighted average (same weights as before)
  return (
    viewScore * 0.3 +
    clickScore * 0.3 +
    favoriteScore * 0.25 +
    messageScore * 0.15
  );
}

/**
 * Calculate recency score based on how recently the property was published
 * Uses exponential decay
 */
function calculateRecencyScore(property: PropertyWithRelations, now: Date): number {
  if (!property.publishedAt) return 20;

  const daysSincePublished =
    (now.getTime() - property.publishedAt.getTime()) / (1000 * 60 * 60 * 24);

  // Exponential decay: 100 * e^(-days/7)
  const decayRate = 7;
  const score = 100 * Math.exp(-daysSincePublished / decayRate);

  // Step bonuses for very recent properties
  if (daysSincePublished < 1) return 100;
  if (daysSincePublished < 7) return Math.max(80, score);
  if (daysSincePublished < 30) return Math.max(60, score);

  return Math.max(20, score);
}

/**
 * Calculate agent boost score based on subscription tier and verification
 */
async function calculateAgentBoost(
  owner: PropertyWithRelations['owner'],
  cachedSubscription?: any
): Promise<number> {
  if (!owner || owner.role !== 'AGENT') return 0;

  let score = 0;
  let activeSubscription = cachedSubscription;

  if (!activeSubscription && owner.id) {
    activeSubscription = await prisma.agentSubscription.findFirst({
      where: {
        userId: owner.id,
        status: 'ACTIVE',
        endDate: { gt: new Date() },
      },
      include: { plan: true },
    });
  }

  if (activeSubscription) {
    score += 50; // Base agent boost

    const planName = activeSubscription.plan.name.toLowerCase();
    if (planName.includes('premium') || planName.includes('enterprise')) {
      score += 30;
    } else if (planName.includes('basic')) {
      score += 10;
    }

    if (owner.agentProfile?.verificationStatus === 'VERIFIED') {
      score += 20;
    }
  } else {
    if (owner.agentProfile?.verificationStatus === 'VERIFIED') {
      score += 15;
    }
  }

  return Math.min(100, score);
}

/**
 * Calculate quality score based on completeness, verification, and data quality
 */
function calculateQualityScore(
  property: PropertyWithRelations,
  owner: PropertyWithRelations['owner']
): number {
  let score = 0;

  // Photo completeness (max 30 points)
  const photoCount = property.photos?.length || 0;
  score += Math.min(30, (photoCount / 10) * 30);

  // Description quality (max 20 points)
  const descLength = property.description?.length || 0;
  score += Math.min(20, (descLength / 500) * 20);

  // Amenities (max 15 points)
  const amenityCount = property.amenities?.length || 0;
  score += Math.min(15, (amenityCount / 5) * 15);

  // Verification (max 20 points)
  if (property.verified) score += 20;
  if (owner?.verified) score += 10;
  if (owner?.agentProfile?.verificationStatus === 'VERIFIED') score += 10;

  // Required fields completeness (max 15 points)
  const requiredFields = ['price', 'bedrooms', 'bathrooms', 'areaSqft', 'address'];
  const filledFields = requiredFields.filter((f) => {
    const value = property[f as keyof PropertyWithRelations];
    return value != null && value !== '';
  }).length;
  score += (filledFields / requiredFields.length) * 15;

  return Math.min(100, score);
}

/**
 * Calculate property score using Z-score normalization for engagement
 * This is much more efficient than the previous O(n²) approach
 */
export async function calculatePropertyScoreZScore(
  property: PropertyWithRelations,
  engagementStats: EngagementStats,
  now: Date = new Date(),
  cachedSubscription?: any
): Promise<PropertyScore> {
  const featuredBoost = calculateFeaturedBoost(property, now);
  const engagementZScore = calculateEngagementZScore(property, engagementStats);
  const recencyScore = calculateRecencyScore(property, now);
  const agentBoost = await calculateAgentBoost(property.owner, cachedSubscription);
  const qualityScore = calculateQualityScore(property, property.owner);

  // Weighted final score (same weights as before)
  const finalScore =
    featuredBoost * 0.30 +
    engagementZScore * 0.25 +
    recencyScore * 0.20 +
    agentBoost * 0.15 +
    qualityScore * 0.10;

  return {
    finalScore: Math.round(finalScore * 100) / 100,
    featuredBoost: Math.round(featuredBoost * 100) / 100,
    engagementZScore: Math.round(engagementZScore * 100) / 100,
    recencyScore: Math.round(recencyScore * 100) / 100,
    agentBoost: Math.round(agentBoost * 100) / 100,
    qualityScore: Math.round(qualityScore * 100) / 100,
  };
}

/**
 * Batch calculate scores for multiple properties using Z-score normalization
 * This is O(n) instead of O(n²) - much more CPU efficient
 */
export async function calculatePropertyScoresBatchZScore(
  properties: PropertyWithRelations[],
  now: Date = new Date()
): Promise<Map<string, PropertyScore>> {
  // CRITICAL SAFEGUARD: Prevent CPU spike by limiting batch size
  const MAX_BATCH_SIZE = 300;
  if (properties.length > MAX_BATCH_SIZE) {
    console.warn(`[PERFORMANCE] calculatePropertyScoresBatchZScore called with ${properties.length} properties, limiting to ${MAX_BATCH_SIZE}`);
    properties = properties.slice(0, MAX_BATCH_SIZE);
  }

  if (properties.length === 0) {
    return new Map();
  }

  // Step 1: Compute engagement statistics in O(n) - single pass
  const engagementStats = computeEngagementStats(properties);

  // Step 2: Batch fetch agent subscriptions (single query)
  const agentUserIds = properties
    .filter((p) => p.owner?.role === 'AGENT' && p.owner?.id)
    .map((p) => p.owner!.id)
    .filter((id, index, self) => self.indexOf(id) === index); // Unique

  const activeSubscriptions = await prisma.agentSubscription.findMany({
    where: {
      userId: { in: agentUserIds },
      status: 'ACTIVE',
      endDate: { gt: now },
    },
    include: { plan: true },
  });

  const subscriptionMap = new Map(
    activeSubscriptions.map((sub) => [sub.userId, sub])
  );

  // Step 3: Calculate scores for each property (O(n) - no nested loops)
  const scoreMap = new Map<string, PropertyScore>();

  for (const property of properties) {
    const cachedSubscription = property.owner
      ? subscriptionMap.get(property.owner.id) || null
      : null;

    const score = await calculatePropertyScoreZScore(
      property,
      engagementStats,
      now,
      cachedSubscription
    );
    scoreMap.set(property.id, score);
  }

  return scoreMap;
}




