import { User, Team, Player, Coach } from "../shared/schema";

export interface SmartRecommendation {
  id: string;
  title: string;
  description: string;
  priority: "critical" | "high" | "medium" | "low";
  complexity: number; // 1-5 scale
  estimatedTime: string;
  category: "setup" | "management" | "analytics" | "engagement" | "performance" | "compliance";
  sportSpecific: boolean;
  benefits: string[];
  prerequisites: string[];
  route: string;
  completed: boolean;
  aiReasoning: string;
  sportContext: string;
  urgencyScore: number; // 1-100
}

export interface SportProfile {
  name: string;
  type: "team" | "individual" | "hybrid";
  teamSize: {
    min: number;
    max: number;
    optimal: number;
  };
  positions: string[];
  keyMetrics: string[];
  commonFormations: string[];
  seasonalFactors: string[];
  complianceRequirements: string[];
  performanceIndicators: string[];
}

export class SmartRecommendationEngine {
  private sportProfiles: Record<string, SportProfile> = {
    rugby: {
      name: "Rugby",
      type: "team",
      teamSize: { min: 15, max: 23, optimal: 18 },
      positions: ["Prop", "Hooker", "Lock", "Flanker", "Number 8", "Scrum-half", "Fly-half", "Centre", "Wing", "Fullback"],
      keyMetrics: ["Tackles", "Carries", "Passes", "Lineout Success", "Scrum Win Rate"],
      commonFormations: ["8-man scrum", "7-man lineout", "Defensive line"],
      seasonalFactors: ["Pre-season fitness", "Competition phase", "Recovery period"],
      complianceRequirements: ["Medical clearances", "Insurance", "Registration"],
      performanceIndicators: ["Territory", "Possession", "Set piece success", "Discipline"]
    },
    football: {
      name: "Football",
      type: "team",
      teamSize: { min: 11, max: 25, optimal: 18 },
      positions: ["Goalkeeper", "Defender", "Midfielder", "Forward"],
      keyMetrics: ["Goals", "Assists", "Passes", "Tackles", "Saves"],
      commonFormations: ["4-4-2", "4-3-3", "3-5-2"],
      seasonalFactors: ["Transfer windows", "League schedule", "Cup competitions"],
      complianceRequirements: ["FIFA registration", "Medical examinations"],
      performanceIndicators: ["Possession", "Shots on target", "Pass accuracy"]
    },
    basketball: {
      name: "Basketball",
      type: "team",
      teamSize: { min: 5, max: 15, optimal: 12 },
      positions: ["Point Guard", "Shooting Guard", "Small Forward", "Power Forward", "Center"],
      keyMetrics: ["Points", "Rebounds", "Assists", "Steals", "Blocks"],
      commonFormations: ["Zone defense", "Man-to-man", "Pick and roll"],
      seasonalFactors: ["Regular season", "Playoffs", "Off-season training"],
      complianceRequirements: ["Physical examinations", "Equipment standards"],
      performanceIndicators: ["Field goal percentage", "Free throw percentage", "Turnovers"]
    },
    cricket: {
      name: "Cricket",
      type: "team",
      teamSize: { min: 11, max: 16, optimal: 14 },
      positions: ["Batsman", "Bowler", "All-rounder", "Wicket-keeper"],
      keyMetrics: ["Runs", "Wickets", "Catches", "Strike Rate", "Economy Rate"],
      commonFormations: ["Field placements", "Bowling rotations"],
      seasonalFactors: ["Season format", "Weather conditions", "Pitch conditions"],
      complianceRequirements: ["Equipment safety", "Playing conditions"],
      performanceIndicators: ["Batting average", "Bowling average", "Run rate"]
    },
    tennis: {
      name: "Tennis",
      type: "individual",
      teamSize: { min: 1, max: 8, optimal: 4 },
      positions: ["Singles Player", "Doubles Player"],
      keyMetrics: ["Aces", "Winners", "Unforced Errors", "Break Points"],
      commonFormations: ["Singles formation", "Doubles formation"],
      seasonalFactors: ["Tournament schedule", "Surface changes"],
      complianceRequirements: ["Ranking requirements", "Drug testing"],
      performanceIndicators: ["First serve percentage", "Break point conversion"]
    },
    badminton: {
      name: "Badminton",
      type: "individual",
      teamSize: { min: 1, max: 6, optimal: 4 },
      positions: ["Singles Player", "Doubles Player"],
      keyMetrics: ["Smashes", "Drops", "Clears", "Rally Length"],
      commonFormations: ["Attack formation", "Defense formation"],
      seasonalFactors: ["Tournament cycles", "Training phases"],
      complianceRequirements: ["Equipment regulations", "Anti-doping"],
      performanceIndicators: ["Shot accuracy", "Rally win percentage"]
    }
  };

  constructor(
    private teams: Team[],
    private players: Player[],
    private coaches: Coach[],
    private user: User
  ) {}

  public generateRecommendations(sportType: string) {
    const sportProfile = this.sportProfiles[sportType.toLowerCase()] || this.sportProfiles.rugby;
    const isTeamSport = sportProfile.type === "team";
    
    // Filter data by organization
    const orgTeams = this.teams.filter(t => t.organizationId === this.user.organizationId);
    const orgPlayers = this.players.filter(p => p.teamId && orgTeams.some(t => t.id === p.teamId));
    const orgCoaches = this.coaches.filter(c => orgTeams.length > 0);

    const recommendations: SmartRecommendation[] = [];
    const insights: string[] = [];

    // Critical Setup Recommendations
    if (orgTeams.length === 0) {
      recommendations.push({
        id: "team-foundation",
        title: `Create Your ${sportProfile.name} Organization`,
        description: `Establish your ${sportProfile.name} team structure with proper branding, colors, and organizational details`,
        priority: "critical",
        complexity: 2,
        estimatedTime: "8 minutes",
        category: "setup",
        sportSpecific: true,
        benefits: [
          "Professional team identity",
          "Organized player management",
          "Structured competition readiness"
        ],
        prerequisites: [],
        route: "/teams",
        completed: false,
        aiReasoning: `${sportProfile.name} requires a foundational team structure to organize players effectively and maintain professional standards`,
        sportContext: `${sportProfile.name} teams need clear identity and structure for ${isTeamSport ? 'team coordination' : 'individual player development'}`,
        urgencyScore: 95
      });
      insights.push("Team foundation is critical for organizational success");
    }

    // Player Management Analysis
    const playerGap = this.analyzePlayerGap(orgPlayers, sportProfile);
    if (playerGap.hasGap) {
      recommendations.push({
        id: "optimize-roster",
        title: `${sportProfile.name} Roster Optimization`,
        description: playerGap.description,
        priority: playerGap.priority,
        complexity: 3,
        estimatedTime: playerGap.estimatedTime,
        category: "management",
        sportSpecific: true,
        benefits: playerGap.benefits,
        prerequisites: orgTeams.length > 0 ? [] : ["team-foundation"],
        route: "/players/register",
        completed: false,
        aiReasoning: playerGap.reasoning,
        sportContext: `${sportProfile.name} optimal team size: ${sportProfile.teamSize.optimal} players`,
        urgencyScore: playerGap.urgencyScore
      });
      insights.push(playerGap.insight);
    }

    // Position-Specific Analysis
    if (isTeamSport && orgPlayers.length > 0) {
      const positionAnalysis = this.analyzePositions(orgPlayers, sportProfile);
      if (positionAnalysis.hasIssues) {
        recommendations.push({
          id: "position-optimization",
          title: `${sportProfile.name} Position Strategy`,
          description: positionAnalysis.description,
          priority: "high",
          complexity: 3,
          estimatedTime: "12 minutes",
          category: "management",
          sportSpecific: true,
          benefits: [
            "Balanced team composition",
            "Strategic flexibility",
            "Improved performance potential"
          ],
          prerequisites: ["optimize-roster"],
          route: "/teams",
          completed: false,
          aiReasoning: positionAnalysis.reasoning,
          sportContext: `${sportProfile.name} requires balanced position coverage for competitive success`,
          urgencyScore: positionAnalysis.urgencyScore
        });
        insights.push(positionAnalysis.insight);
      }
    }

    // Coaching Structure
    if (isTeamSport) {
      const coachingAnalysis = this.analyzeCoaching(orgCoaches, orgTeams, sportProfile);
      if (coachingAnalysis.needsImprovement) {
        recommendations.push({
          id: "coaching-structure",
          title: `${sportProfile.name} Coaching Excellence`,
          description: coachingAnalysis.description,
          priority: coachingAnalysis.priority,
          complexity: 2,
          estimatedTime: "10 minutes",
          category: "management",
          sportSpecific: true,
          benefits: coachingAnalysis.benefits,
          prerequisites: orgTeams.length > 0 ? [] : ["team-foundation"],
          route: "/coaches",
          completed: false,
          aiReasoning: coachingAnalysis.reasoning,
          sportContext: `${sportProfile.name} coaching requirements vary by team complexity and competitive level`,
          urgencyScore: coachingAnalysis.urgencyScore
        });
        insights.push(coachingAnalysis.insight);
      }
    }

    // Performance Analytics
    if (orgPlayers.length >= 3) {
      recommendations.push({
        id: "performance-analytics",
        title: `${sportProfile.name} Performance Intelligence`,
        description: `Implement advanced analytics to track ${sportProfile.keyMetrics.join(', ')} and other ${sportProfile.name}-specific metrics`,
        priority: "medium",
        complexity: 4,
        estimatedTime: "15 minutes",
        category: "analytics",
        sportSpecific: true,
        benefits: [
          "Data-driven decision making",
          "Player development insights",
          "Competitive advantage",
          "Performance trend analysis"
        ],
        prerequisites: ["optimize-roster"],
        route: "/analytics",
        completed: false,
        aiReasoning: `${sportProfile.name} performance can be significantly improved through systematic tracking of key metrics`,
        sportContext: `${sportProfile.name} analytics focus on: ${sportProfile.performanceIndicators.join(', ')}`,
        urgencyScore: 60
      });
    }

    // Attendance & Engagement
    recommendations.push({
      id: "engagement-system",
      title: `${sportProfile.name} Engagement Platform`,
      description: `Set up attendance tracking, communication system, and engagement tools tailored for ${sportProfile.name}`,
      priority: "medium",
      complexity: 3,
      estimatedTime: "12 minutes",
      category: "engagement",
      sportSpecific: true,
      benefits: [
        "Improved attendance rates",
        "Better communication",
        "Enhanced team culture",
        "Automated notifications"
      ],
      prerequisites: orgPlayers.length > 0 ? [] : ["optimize-roster"],
      route: "/attendance",
      completed: false,
      aiReasoning: `${sportProfile.name} success depends heavily on consistent participation and team communication`,
      sportContext: `${sportProfile.name} engagement factors: ${sportProfile.seasonalFactors.join(', ')}`,
      urgencyScore: 70
    });

    // Compliance & Safety
    if (sportProfile.complianceRequirements.length > 0) {
      recommendations.push({
        id: "compliance-framework",
        title: `${sportProfile.name} Compliance & Safety`,
        description: `Ensure compliance with ${sportProfile.complianceRequirements.join(', ')} and safety protocols`,
        priority: "high",
        complexity: 3,
        estimatedTime: "20 minutes",
        category: "compliance",
        sportSpecific: true,
        benefits: [
          "Legal compliance",
          "Player safety",
          "Risk mitigation",
          "Professional standards"
        ],
        prerequisites: ["team-foundation"],
        route: "/settings",
        completed: false,
        aiReasoning: `${sportProfile.name} has specific compliance requirements that must be addressed for safe and legal operation`,
        sportContext: `${sportProfile.name} compliance: ${sportProfile.complianceRequirements.join(', ')}`,
        urgencyScore: 85
      });
    }

    // Calculate current setup score
    const setupScore = this.calculateSetupScore(orgTeams, orgPlayers, orgCoaches, sportProfile);
    const readinessLevel = this.determineReadinessLevel(setupScore);
    
    // Sort recommendations by urgency score
    recommendations.sort((a, b) => b.urgencyScore - a.urgencyScore);

    return {
      recommendations,
      analysis: {
        sportType: sportProfile.name,
        isTeamSport,
        currentSetupScore: setupScore,
        readinessLevel,
        keyInsights: insights,
        nextMilestone: this.getNextMilestone(setupScore, sportProfile)
      }
    };
  }

  private analyzePlayerGap(players: Player[], profile: SportProfile) {
    const playerCount = players.length;
    const optimal = profile.teamSize.optimal;
    const min = profile.teamSize.min;

    if (playerCount === 0) {
      return {
        hasGap: true,
        description: `Build your ${profile.name} roster from scratch with strategic player recruitment`,
        priority: "critical" as const,
        estimatedTime: "5 minutes per player",
        benefits: ["Complete team foundation", "Strategic player selection", "Balanced roster development"],
        reasoning: "No players registered - this is the foundation of any sports organization",
        insight: "Player recruitment is the cornerstone of team success",
        urgencyScore: 90
      };
    }

    if (playerCount < min) {
      return {
        hasGap: true,
        description: `Recruit ${min - playerCount} more players to reach minimum viable team size for ${profile.name}`,
        priority: "critical" as const,
        estimatedTime: `${(min - playerCount) * 5} minutes`,
        benefits: ["Minimum team viability", "Competition readiness", "Training effectiveness"],
        reasoning: `${profile.name} requires minimum ${min} players for effective training and competition`,
        insight: `Below minimum team size (${playerCount}/${min})`,
        urgencyScore: 85
      };
    }

    if (playerCount < optimal) {
      return {
        hasGap: true,
        description: `Add ${optimal - playerCount} more players to reach optimal team size and competitive depth`,
        priority: "high" as const,
        estimatedTime: `${(optimal - playerCount) * 5} minutes`,
        benefits: ["Optimal team depth", "Injury coverage", "Competition flexibility", "Training quality"],
        reasoning: `${profile.name} performs best with ${optimal} players for rotation and specialization`,
        insight: `Approaching optimal size (${playerCount}/${optimal})`,
        urgencyScore: 70
      };
    }

    return {
      hasGap: false,
      description: "",
      priority: "low" as const,
      estimatedTime: "",
      benefits: [],
      reasoning: "",
      insight: "",
      urgencyScore: 0
    };
  }

  private analyzePositions(players: Player[], profile: SportProfile) {
    const positionCounts = players.reduce((acc, player) => {
      if (player.position) {
        acc[player.position] = (acc[player.position] || 0) + 1;
      }
      return acc;
    }, {} as Record<string, number>);

    const assignedPlayers = players.filter(p => p.position).length;
    const unassignedPlayers = players.length - assignedPlayers;

    if (unassignedPlayers > players.length * 0.3) {
      return {
        hasIssues: true,
        description: `Assign positions to ${unassignedPlayers} players for optimal ${profile.name} formation and strategy`,
        reasoning: `${profile.name} requires clear position assignments for tactical execution and player development`,
        insight: `${unassignedPlayers} players need position assignments`,
        urgencyScore: 75
      };
    }

    const missingPositions = profile.positions.filter(pos => !positionCounts[pos]);
    if (missingPositions.length > 0) {
      return {
        hasIssues: true,
        description: `Address position gaps in ${missingPositions.join(', ')} for complete ${profile.name} coverage`,
        reasoning: `${profile.name} strategy requires coverage across all key positions`,
        insight: `Missing key positions: ${missingPositions.join(', ')}`,
        urgencyScore: 65
      };
    }

    return {
      hasIssues: false,
      description: "",
      reasoning: "",
      insight: "",
      urgencyScore: 0
    };
  }

  private analyzeCoaching(coaches: Coach[], teams: Team[], profile: SportProfile) {
    const coachCount = coaches.length;
    const teamCount = teams.length;

    if (coachCount === 0 && teamCount > 0) {
      return {
        needsImprovement: true,
        description: `Recruit qualified ${profile.name} coaches to provide professional training and strategic guidance`,
        priority: "high" as const,
        benefits: ["Professional training", "Strategic development", "Player mentorship", "Competitive edge"],
        reasoning: `${profile.name} teams require experienced coaching for proper technique and strategy development`,
        insight: "No coaches assigned to active teams",
        urgencyScore: 80
      };
    }

    if (coachCount < teamCount) {
      return {
        needsImprovement: true,
        description: `Add ${teamCount - coachCount} more coaches to ensure adequate coaching coverage for all teams`,
        priority: "medium" as const,
        benefits: ["Adequate coaching ratio", "Focused attention", "Specialized training"],
        reasoning: `Each ${profile.name} team benefits from dedicated coaching attention`,
        insight: `Coaching gap: ${coachCount} coaches for ${teamCount} teams`,
        urgencyScore: 60
      };
    }

    return {
      needsImprovement: false,
      description: "",
      priority: "low" as const,
      benefits: [],
      reasoning: "",
      insight: "",
      urgencyScore: 0
    };
  }

  private calculateSetupScore(teams: Team[], players: Player[], coaches: Coach[], profile: SportProfile): number {
    let score = 0;
    
    // Team foundation (25 points)
    if (teams.length > 0) score += 25;
    
    // Player adequacy (35 points)
    const playerRatio = players.length / profile.teamSize.optimal;
    score += Math.min(35, Math.round(playerRatio * 35));
    
    // Position coverage (20 points)
    if (profile.type === "team") {
      const assignedPositions = new Set(players.filter(p => p.position).map(p => p.position));
      const positionCoverage = assignedPositions.size / profile.positions.length;
      score += Math.round(positionCoverage * 20);
    } else {
      score += 15; // Individual sports get partial credit
    }
    
    // Coaching (20 points)
    if (profile.type === "team") {
      const coachingScore = Math.min(20, coaches.length * 10);
      score += coachingScore;
    } else {
      score += 10; // Individual sports need less coaching
    }
    
    return Math.min(100, score);
  }

  private determineReadinessLevel(score: number): string {
    if (score >= 90) return "Championship Ready";
    if (score >= 75) return "Competition Ready";
    if (score >= 50) return "Training Ready";
    if (score >= 25) return "Foundation Built";
    return "Getting Started";
  }

  private getNextMilestone(score: number, profile: SportProfile): string {
    if (score < 25) return `Establish ${profile.name} team foundation`;
    if (score < 50) return `Build core player roster`;
    if (score < 75) return `Optimize positions and coaching`;
    if (score < 90) return `Implement advanced analytics`;
    return `Achieve competitive excellence`;
  }
}