import { storage } from "./storage";

export interface OnboardingRecommendation {
  id: string;
  title: string;
  description: string;
  priority: "critical" | "high" | "medium" | "low";
  category: "setup" | "management" | "analytics" | "engagement" | "performance" | "compliance";
  estimatedTime: string;
  benefits: string[];
  actionUrl: string;
  completed: boolean;
  aiReasoning: string;
  sportSpecific: boolean;
  urgencyScore: number; // 1-100
  prerequisites: string[];
  difficulty: "beginner" | "intermediate" | "advanced";
}

export interface SportAnalysis {
  sportType: string;
  currentSetup: {
    playersCount: number;
    teamsCount: number;
    coachesCount: number;
    hasPositions: boolean;
    hasRoster: boolean;
    hasBiometrics: boolean;
    hasAttendance: boolean;
  };
  setupScore: number; // 0-100
  readinessLevel: string;
  nextMilestone: string;
  recommendations: OnboardingRecommendation[];
}

export class SmartOnboardingEngine {
  private sportProfiles = {
    "Football": {
      type: "team",
      minPlayers: 11,
      optimalPlayers: 25,
      positions: ["Quarterback", "Running Back", "Wide Receiver", "Tight End", "Offensive Line", "Defensive Back", "Linebacker", "Defensive Line", "Kicker", "Punter"],
      keyMetrics: ["Passing Yards", "Rushing Yards", "Tackles", "Interceptions", "Touchdowns"],
      formations: ["4-3", "3-4", "Nickel", "Dime"],
      compliance: ["Equipment Safety", "Injury Protocols", "Player Eligibility"]
    },
    "Basketball": {
      type: "team",
      minPlayers: 5,
      optimalPlayers: 15,
      positions: ["Point Guard", "Shooting Guard", "Small Forward", "Power Forward", "Center"],
      keyMetrics: ["Points", "Rebounds", "Assists", "Steals", "Blocks", "Field Goal %"],
      formations: ["Man-to-Man", "Zone Defense", "Press", "Pick and Roll"],
      compliance: ["Drug Testing", "Academic Eligibility", "Physical Exams"]
    },
    "Rugby": {
      type: "team",
      minPlayers: 15,
      optimalPlayers: 30,
      positions: ["Prop", "Hooker", "Lock", "Flanker", "Number 8", "Scrum Half", "Fly Half", "Centre", "Wing", "Fullback"],
      keyMetrics: ["Tries", "Conversions", "Tackles", "Meters Gained", "Lineout Success"],
      formations: ["15s", "7s", "10s"],
      compliance: ["World Rugby Regulations", "Anti-Doping", "Player Welfare"]
    },
    "Soccer": {
      type: "team",
      minPlayers: 11,
      optimalPlayers: 25,
      positions: ["Goalkeeper", "Defender", "Midfielder", "Forward"],
      keyMetrics: ["Goals", "Assists", "Passes", "Tackles", "Saves"],
      formations: ["4-4-2", "4-3-3", "3-5-2", "4-2-3-1"],
      compliance: ["FIFA Regulations", "Player Registration", "Medical Clearance"]
    },
    "Cricket": {
      type: "team",
      minPlayers: 11,
      optimalPlayers: 16,
      positions: ["Batsman", "Bowler", "Wicket Keeper", "All Rounder"],
      keyMetrics: ["Runs", "Wickets", "Catches", "Strike Rate", "Economy Rate"],
      formations: ["Test", "ODI", "T20"],
      compliance: ["ICC Regulations", "Anti-Corruption", "Equipment Standards"]
    },
    "Tennis": {
      type: "individual",
      minPlayers: 1,
      optimalPlayers: 8,
      positions: ["Singles Player", "Doubles Player"],
      keyMetrics: ["Match Wins", "Set Wins", "Aces", "Winners", "Unforced Errors"],
      formations: ["Singles", "Doubles"],
      compliance: ["ITF Rules", "Drug Testing", "Ranking Requirements"]
    },
    "Baseball": {
      type: "team",
      minPlayers: 9,
      optimalPlayers: 25,
      positions: ["Pitcher", "Catcher", "First Base", "Second Base", "Third Base", "Shortstop", "Left Field", "Center Field", "Right Field"],
      keyMetrics: ["Batting Average", "ERA", "Home Runs", "RBIs", "Stolen Bases"],
      formations: ["Standard", "Defensive Shifts"],
      compliance: ["MLB Rules", "Drug Policy", "Player Development"]
    },
    "Hockey": {
      type: "team",
      minPlayers: 6,
      optimalPlayers: 20,
      positions: ["Goalie", "Defenseman", "Forward", "Center", "Winger"],
      keyMetrics: ["Goals", "Assists", "Plus/Minus", "Penalty Minutes", "Save %"],
      formations: ["Even Strength", "Power Play", "Penalty Kill"],
      compliance: ["NHL/IIHF Rules", "Equipment Safety", "Concussion Protocol"]
    },
    "Volleyball": {
      type: "team",
      minPlayers: 6,
      optimalPlayers: 12,
      positions: ["Outside Hitter", "Middle Blocker", "Setter", "Libero", "Opposite", "Defensive Specialist"],
      keyMetrics: ["Kills", "Blocks", "Digs", "Assists", "Aces"],
      formations: ["6-2", "5-1", "4-2"],
      compliance: ["FIVB Rules", "Net Height Standards", "Player Rotation"]
    },
    "Badminton": {
      type: "individual",
      minPlayers: 1,
      optimalPlayers: 8,
      positions: ["Singles Player", "Doubles Player"],
      keyMetrics: ["Match Wins", "Rally Length", "Smash Speed", "Drop Shots", "Clear Distance"],
      formations: ["Singles", "Doubles", "Mixed Doubles"],
      compliance: ["BWF Regulations", "Equipment Standards", "Court Specifications"]
    }
  };

  constructor(private userId: string) {}

  async generateSmartRecommendations(sportType: string): Promise<SportAnalysis> {
    // Get current setup data
    const players = await storage.getPlayers();
    const teams = await storage.getTeams();
    const coaches = await storage.getCoaches();
    
    // Filter by user's organization if applicable
    const userPlayers = players.filter(p => p.userId === this.userId);
    const userTeams = teams.filter(t => t.userId === this.userId);
    const userCoaches = coaches.filter(c => c.userId === this.userId);

    const currentSetup = {
      playersCount: userPlayers.length,
      teamsCount: userTeams.length,
      coachesCount: userCoaches.length,
      hasPositions: userPlayers.some(p => p.position),
      hasRoster: userTeams.some(t => t.playerIds && t.playerIds.length > 0),
      hasBiometrics: false, // This would check if any biometric data exists
      hasAttendance: false  // This would check if attendance tracking is configured
    };

    const sportProfile = this.sportProfiles[sportType];
    if (!sportProfile) {
      throw new Error(`Sport profile not found for: ${sportType}`);
    }

    // Calculate setup score
    const setupScore = this.calculateSetupScore(currentSetup, sportProfile);
    const readinessLevel = this.getReadinessLevel(setupScore);
    const nextMilestone = this.getNextMilestone(setupScore, sportProfile);

    // Generate recommendations
    const recommendations = this.generateRecommendations(currentSetup, sportProfile, sportType);

    return {
      sportType,
      currentSetup,
      setupScore,
      readinessLevel,
      nextMilestone,
      recommendations
    };
  }

  private calculateSetupScore(setup: any, profile: any): number {
    let score = 0;

    // Player count (30 points)
    if (setup.playersCount >= profile.minPlayers) {
      score += 20;
      if (setup.playersCount >= profile.optimalPlayers * 0.8) {
        score += 10;
      }
    }

    // Team structure (20 points)
    if (setup.teamsCount > 0) score += 10;
    if (setup.coachesCount > 0) score += 10;

    // Position assignments (20 points)
    if (setup.hasPositions) score += 20;

    // Roster management (15 points)
    if (setup.hasRoster) score += 15;

    // Advanced features (15 points)
    if (setup.hasBiometrics) score += 8;
    if (setup.hasAttendance) score += 7;

    return Math.min(score, 100);
  }

  private getReadinessLevel(score: number): string {
    if (score >= 90) return "Championship Ready";
    if (score >= 75) return "Competition Ready";
    if (score >= 60) return "Training Ready";
    if (score >= 40) return "Team Building";
    if (score >= 20) return "Foundation Building";
    return "Getting Started";
  }

  private getNextMilestone(score: number, profile: any): string {
    if (score < 20) return `Add ${profile.minPlayers} players to reach minimum team size`;
    if (score < 40) return "Assign coaches and establish team structure";
    if (score < 60) return "Configure player positions and formations";
    if (score < 75) return "Set up attendance tracking and performance metrics";
    if (score < 90) return "Implement advanced analytics and biometric monitoring";
    return "Optimize for peak performance and competition readiness";
  }

  private generateRecommendations(setup: any, profile: any, sportType: string): OnboardingRecommendation[] {
    const recommendations: OnboardingRecommendation[] = [];

    // Critical recommendations
    if (setup.playersCount < profile.minPlayers) {
      recommendations.push({
        id: "add-players",
        title: "Add Players to Your Team",
        description: `You need at least ${profile.minPlayers} players for ${sportType}. Currently you have ${setup.playersCount}.`,
        priority: "critical",
        category: "setup",
        estimatedTime: "15-30 minutes",
        benefits: ["Meet minimum team requirements", "Enable team formation", "Start competitive play"],
        actionUrl: "/players/register",
        completed: false,
        aiReasoning: `${sportType} requires a minimum of ${profile.minPlayers} players to form a complete team. This is essential for gameplay and competition eligibility.`,
        sportSpecific: true,
        urgencyScore: 95,
        prerequisites: [],
        difficulty: "beginner"
      });
    }

    // High priority recommendations
    if (setup.teamsCount === 0) {
      recommendations.push({
        id: "create-team",
        title: "Create Your First Team",
        description: "Set up your team structure and organization to manage players effectively.",
        priority: "high",
        category: "setup",
        estimatedTime: "10-15 minutes",
        benefits: ["Organize players", "Enable roster management", "Track team performance"],
        actionUrl: "/teams/create",
        completed: false,
        aiReasoning: "Team structure is fundamental for organizing players, managing rosters, and tracking collective performance in team sports.",
        sportSpecific: false,
        urgencyScore: 85,
        prerequisites: ["add-players"],
        difficulty: "beginner"
      });
    }

    if (setup.coachesCount === 0) {
      recommendations.push({
        id: "add-coaches",
        title: "Add Coaching Staff",
        description: "Assign coaches to provide leadership and training guidance for your team.",
        priority: "high",
        category: "management",
        estimatedTime: "5-10 minutes",
        benefits: ["Professional guidance", "Training coordination", "Strategy development"],
        actionUrl: "/coaches/register",
        completed: false,
        aiReasoning: "Coaching staff provides essential leadership, training coordination, and strategic guidance for team development and performance.",
        sportSpecific: false,
        urgencyScore: 80,
        prerequisites: [],
        difficulty: "beginner"
      });
    }

    // Medium priority recommendations
    if (!setup.hasPositions && profile.positions.length > 0) {
      recommendations.push({
        id: "assign-positions",
        title: `Configure ${sportType} Positions`,
        description: `Set up specific positions for ${sportType}: ${profile.positions.slice(0, 3).join(", ")}${profile.positions.length > 3 ? ` and ${profile.positions.length - 3} more` : ""}.`,
        priority: "medium",
        category: "setup",
        estimatedTime: "20-30 minutes",
        benefits: ["Strategic player placement", "Formation planning", "Performance tracking by position"],
        actionUrl: "/teams/positions",
        completed: false,
        aiReasoning: `Position assignments are crucial for ${sportType} strategy and formation planning. Each position has specific roles and responsibilities.`,
        sportSpecific: true,
        urgencyScore: 70,
        prerequisites: ["create-team"],
        difficulty: "intermediate"
      });
    }

    if (!setup.hasRoster) {
      recommendations.push({
        id: "create-roster",
        title: "Build Your Team Roster",
        description: "Assign players to teams and create your starting lineup.",
        priority: "medium",
        category: "management",
        estimatedTime: "15-25 minutes",
        benefits: ["Starting lineup selection", "Substitute management", "Match preparation"],
        actionUrl: "/roster",
        completed: false,
        aiReasoning: "Roster management enables strategic player selection, formation planning, and efficient match preparation.",
        sportSpecific: false,
        urgencyScore: 65,
        prerequisites: ["create-team", "assign-positions"],
        difficulty: "intermediate"
      });
    }

    // Analytics and performance recommendations
    if (setup.playersCount >= profile.minPlayers && !setup.hasAttendance) {
      recommendations.push({
        id: "setup-attendance",
        title: "Enable Attendance Tracking",
        description: "Monitor training sessions and match attendance to ensure team commitment.",
        priority: "medium",
        category: "analytics",
        estimatedTime: "10-15 minutes",
        benefits: ["Monitor commitment", "Training consistency", "Performance correlation"],
        actionUrl: "/attendance",
        completed: false,
        aiReasoning: "Attendance tracking helps identify commitment levels and correlate training consistency with performance outcomes.",
        sportSpecific: false,
        urgencyScore: 60,
        prerequisites: ["create-roster"],
        difficulty: "beginner"
      });
    }

    // Advanced recommendations
    if (setup.playersCount >= profile.minPlayers && !setup.hasBiometrics) {
      recommendations.push({
        id: "setup-biometrics",
        title: "Configure Biometric Monitoring",
        description: "Set up advanced player monitoring for fitness and performance tracking.",
        priority: "low",
        category: "performance",
        estimatedTime: "30-45 minutes",
        benefits: ["Fitness monitoring", "Injury prevention", "Performance optimization"],
        actionUrl: "/biometric",
        completed: false,
        aiReasoning: "Biometric monitoring provides valuable insights into player fitness, helps prevent injuries, and optimizes training programs.",
        sportSpecific: false,
        urgencyScore: 40,
        prerequisites: ["setup-attendance"],
        difficulty: "advanced"
      });
    }

    // Sport-specific compliance
    recommendations.push({
      id: "compliance-setup",
      title: `${sportType} Compliance Setup`,
      description: `Ensure compliance with ${profile.compliance.join(", ")} requirements.`,
      priority: "medium",
      category: "compliance",
      estimatedTime: "20-40 minutes",
      benefits: ["Regulatory compliance", "Competition eligibility", "Safety standards"],
      actionUrl: "/settings",
      completed: false,
      aiReasoning: `Compliance with ${sportType} regulations is essential for competition eligibility and maintaining safety standards.`,
      sportSpecific: true,
      urgencyScore: 55,
      prerequisites: ["create-team"],
      difficulty: "intermediate"
    });

    // Sort by urgency score and priority
    return recommendations.sort((a, b) => {
      const priorityOrder = { critical: 4, high: 3, medium: 2, low: 1 };
      if (priorityOrder[a.priority] !== priorityOrder[b.priority]) {
        return priorityOrder[b.priority] - priorityOrder[a.priority];
      }
      return b.urgencyScore - a.urgencyScore;
    });
  }
}

export async function getSmartOnboardingData(userId: string, sportType: string): Promise<SportAnalysis> {
  const engine = new SmartOnboardingEngine(userId);
  return await engine.generateSmartRecommendations(sportType);
}