# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def university_basketball_optimization():
    """Optimize resource allocation for university basketball teams"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Assuming the total resources available is a parameter
    total_resources_available = 400  # Example value, adjust as needed
    
    # Coefficients from basketball_match.All_Games_Percent
    win_percentages = [0.75, 0.6, 0.85]
    
    # Constraints from resource_constraints
    min_allocations = [50, 60, 70]
    max_allocations = [200, 180, 190]
    
    # Validate array lengths
    n_teams = len(win_percentages)
    assert len(min_allocations) == len(max_allocations) == n_teams, "Array length mismatch"
    
    # 3. SETS
    model.Teams = pyo.RangeSet(1, n_teams)
    
    # 4. PARAMETERS
    model.win_percent = pyo.Param(model.Teams, initialize={i+1: win_percentages[i] for i in range(n_teams)})
    model.min_alloc = pyo.Param(model.Teams, initialize={i+1: min_allocations[i] for i in range(n_teams)})
    model.max_alloc = pyo.Param(model.Teams, initialize={i+1: max_allocations[i] for i in range(n_teams)})
    
    # 5. VARIABLES
    model.resource_allocation = pyo.Var(model.Teams, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.win_percent[i] * model.resource_allocation[i] for i in model.Teams)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total resources constraint
    def total_resources_rule(model):
        return sum(model.resource_allocation[i] for i in model.Teams) <= total_resources_available
    model.total_resources_constraint = pyo.Constraint(rule=total_resources_rule)
    
    # Minimum and maximum allocation constraints
    def min_allocation_rule(model, i):
        return model.resource_allocation[i] >= model.min_alloc[i]
    model.min_allocation_constraint = pyo.Constraint(model.Teams, rule=min_allocation_rule)
    
    def max_allocation_rule(model, i):
        return model.resource_allocation[i] <= model.max_alloc[i]
    model.max_allocation_constraint = pyo.Constraint(model.Teams, rule=max_allocation_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective):.3f}")
        
        # Extract variable values
        print("\nResource Allocation:")
        for i in model.Teams:
            allocation_val = pyo.value(model.resource_allocation[i])
            print(f"Team {i}: {allocation_val:.3f}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

# Run the optimization
university_basketball_optimization()