# Complete PYOMO implementation

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

def concert_singer_optimization():
    """Concert Singer Optimization Model"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the problem statement
    concert_stadium_mapping = [(1, 101), (2, 102), (3, 103)]
    attendance_coefficients = {
        (1, 101): 120.0,
        (1, 102): 180.0,
        (2, 102): 250.0,
        (2, 103): 300.0,
        (3, 103): 400.0
    }
    stadium_capacity = {
        101: 5000,
        102: 10000,
        103: 15000
    }
    
    # 3. SETS
    model.Concerts = pyo.Set(initialize=set(i for i, _ in concert_stadium_mapping))
    model.Stadiums = pyo.Set(initialize=set(j for _, j in concert_stadium_mapping))
    model.ConcertStadiumPairs = pyo.Set(initialize=concert_stadium_mapping)
    
    # 4. PARAMETERS
    model.AttendanceCoefficient = pyo.Param(model.ConcertStadiumPairs, initialize=attendance_coefficients)
    model.StadiumCapacity = pyo.Param(model.Stadiums, initialize=stadium_capacity)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.ConcertStadiumPairs, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.AttendanceCoefficient[i, j] * model.x[i, j] for i, j in model.ConcertStadiumPairs)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Stadium Capacity Constraints
    def stadium_capacity_rule(model, j):
        return sum(model.AttendanceCoefficient[i, j] * model.x[i, j] for i in model.Concerts if (i, j) in model.ConcertStadiumPairs) <= model.StadiumCapacity[j]
    model.stadium_capacity_constraint = pyo.Constraint(model.Stadiums, rule=stadium_capacity_rule)
    
    # Concert Venue Assignment Constraints
    def concert_venue_rule(model, i):
        return sum(model.x[i, j] for j in model.Stadiums if (i, j) in model.ConcertStadiumPairs) >= 1
    model.concert_venue_constraint = pyo.Constraint(model.Concerts, rule=concert_venue_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)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i, j in model.ConcertStadiumPairs:
            x_val = pyo.value(model.x[i, j])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i},{j}] = {int(x_val)}")
        
    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
concert_singer_optimization()