import { Controller, Get, Param, Req } from '@nestjs/common';
import { PatternAnalysisService } from './pattern-analysis.service';
import { PredictionService } from './prediction.service';

@Controller('api/v1/insights')
export class InsightsController {
  constructor(
    private readonly patternAnalysisService: PatternAnalysisService,
    private readonly predictionService: PredictionService,
  ) {}

  /**
   * GET /api/v1/insights/{childId}/patterns
   * Get AI-detected patterns for a child
   */
  @Get(':childId/patterns')
  async getPatterns(@Req() req: any, @Param('childId') childId: string) {
    const patterns = await this.patternAnalysisService.analyzePatterns(
      childId,
      7,
    );

    // Format response to match API specification
    return {
      success: true,
      data: {
        sleepPatterns: patterns.sleep
          ? {
              averageNightSleep: this.parseHoursFromMinutes(
                patterns.sleep.averageDuration,
              ),
              averageDaySleep: patterns.sleep.napCount * 1.5, // Estimate
              optimalBedtime: patterns.sleep.averageBedtime,
              wakeWindows: this.calculateWakeWindows(patterns.sleep),
              trend: patterns.sleep.trend,
              insights: this.formatSleepInsights(patterns.sleep),
            }
          : null,
        feedingPatterns: patterns.feeding
          ? {
              averageIntake: this.estimateAverageIntake(patterns.feeding),
              feedingIntervals: this.formatFeedingIntervals(
                patterns.feeding.averageInterval,
              ),
              preferredSide: this.extractPreferredSide(patterns.feeding),
              insights: this.formatFeedingInsights(patterns.feeding),
            }
          : null,
      },
    };
  }

  /**
   * GET /api/v1/insights/{childId}/predictions
   * Get predictive suggestions
   */
  @Get(':childId/predictions')
  async getPredictions(@Req() req: any, @Param('childId') childId: string) {
    const predictions =
      await this.predictionService.generatePredictions(childId);

    // Format response to match API specification
    return {
      success: true,
      data: {
        nextNapTime: predictions.sleep.nextNapTime
          ? {
              predicted: predictions.sleep.nextNapTime.toISOString(),
              confidence: predictions.sleep.nextNapConfidence,
              wakeWindow: predictions.sleep.optimalWakeWindows[0] || 120,
            }
          : null,
        nextFeedingTime: predictions.feeding.nextFeedingTime
          ? {
              predicted: predictions.feeding.nextFeedingTime.toISOString(),
              confidence: predictions.feeding.confidence,
            }
          : null,
        growthSpurt: this.predictGrowthSpurt(predictions),
      },
    };
  }

  /**
   * Helper: Parse hours from minutes
   */
  private parseHoursFromMinutes(minutes: number): number {
    return Math.round((minutes / 60) * 10) / 10;
  }

  /**
   * Helper: Calculate wake windows from sleep pattern
   */
  private calculateWakeWindows(sleepPattern: any): number[] {
    // Return typical wake windows based on nap count
    const napCount = Math.round(sleepPattern.napCount);
    if (napCount >= 3) return [90, 120, 150, 180];
    if (napCount === 2) return [120, 150, 180];
    return [150, 180, 240];
  }

  /**
   * Helper: Format sleep insights
   */
  private formatSleepInsights(sleepPattern: any): string[] {
    const insights: string[] = [];

    if (sleepPattern.consistency > 0.8) {
      insights.push(
        `Excellent sleep consistency at ${Math.round(sleepPattern.consistency * 100)}%`,
      );
    }

    if (sleepPattern.averageBedtime) {
      insights.push(`Consistent bedtime around ${sleepPattern.averageBedtime}`);
    }

    if (sleepPattern.trend === 'improving') {
      insights.push('Sleep duration has been improving');
    } else if (sleepPattern.trend === 'declining') {
      insights.push('Sleep duration has been decreasing recently');
    }

    return insights;
  }

  /**
   * Helper: Format feeding intervals
   */
  private formatFeedingIntervals(averageInterval: number): number[] {
    // Generate typical intervals around average
    const base = averageInterval;
    return [Math.max(1.5, base - 0.5), base, base, Math.min(6, base + 0.5)].map(
      (v) => Math.round(v * 10) / 10,
    );
  }

  /**
   * Helper: Extract preferred feeding side
   */
  private extractPreferredSide(feedingPattern: any): string | undefined {
    // Check metadata for preferred side
    const methods = Object.keys(feedingPattern.feedingMethod);
    if (methods.includes('nursing_left')) return 'left';
    if (methods.includes('nursing_right')) return 'right';
    return undefined;
  }

  /**
   * Helper: Format feeding insights
   */
  private formatFeedingInsights(feedingPattern: any): string[] {
    const insights: string[] = [];

    if (feedingPattern.trend === 'increasing') {
      insights.push('Feeding frequency is increasing');
    } else if (feedingPattern.trend === 'decreasing') {
      insights.push(
        'Feeding intervals increasing - may be ready for longer stretches',
      );
    }

    if (feedingPattern.consistency > 0.75) {
      insights.push('Well-established feeding routine');
    }

    return insights;
  }

  /**
   * Helper: Estimate average intake
   */
  private estimateAverageIntake(feedingPattern: any): number {
    // Estimate based on feeding frequency (oz per 24 hours)
    const feedingsPerDay = (24 / feedingPattern.averageInterval) * 0.9;
    const avgOzPerFeeding = 4; // Typical for 3-6 month old
    return Math.round(feedingsPerDay * avgOzPerFeeding);
  }

  /**
   * Helper: Predict growth spurt
   */
  private predictGrowthSpurt(predictions: any): {
    likelihood: number;
    expectedIn: string;
    symptoms: string[];
  } {
    // Simple heuristic for growth spurt prediction
    // Typically occur around 3 weeks, 6 weeks, 3 months, 6 months
    const likelihood = 0.5; // Placeholder

    return {
      likelihood: Math.round(likelihood * 100) / 100,
      expectedIn: '5-7 days',
      symptoms: ['increased feeding', 'fussiness', 'disrupted sleep'],
    };
  }
}
