# Complete PYOMO implementation

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

def cinema_optimization():
    """Cinema scheduling optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Assuming data is provided as lists or dictionaries
    cinema_ids = [1, 2, 3]
    film_ids = [101, 102, 103]
    
    # Cinema data
    capacities = {1: 120, 2: 180, 3: 250}
    max_screenings_per_day = {1: 5, 2: 6, 3: 7}
    
    # Film pricing data
    prices = {101: 12.0, 102: 15.0, 103: 10.0}
    
    # Average attendance per screening (assumed data)
    avg_attendance = {101: 100, 102: 150, 103: 200}
    
    # CRITICAL: Validate data lengths before indexing
    assert len(capacities) == len(max_screenings_per_day) == len(cinema_ids), "Cinema data length mismatch"
    assert len(prices) == len(avg_attendance) == len(film_ids), "Film data length mismatch"
    
    # 3. SETS
    model.C = pyo.Set(initialize=cinema_ids)
    model.F = pyo.Set(initialize=film_ids)
    
    # 4. PARAMETERS
    model.capacity = pyo.Param(model.C, initialize=capacities)
    model.max_screenings = pyo.Param(model.C, initialize=max_screenings_per_day)
    model.price = pyo.Param(model.F, initialize=prices)
    model.avg_attendance = pyo.Param(model.F, initialize=avg_attendance)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.C, model.F, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.price[j] * model.x[i, j] for i in model.C for j in model.F)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Maximum screenings per cinema
    def max_screenings_rule(model, i):
        return sum(model.x[i, j] for j in model.F) <= model.max_screenings[i]
    model.max_screenings_constraint = pyo.Constraint(model.C, rule=max_screenings_rule)
    
    # Seating capacity constraint
    def capacity_rule(model, i, j):
        return model.avg_attendance[j] * model.x[i, j] <= model.capacity[i]
    model.capacity_constraint = pyo.Constraint(model.C, model.F, rule=capacity_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("\nScreening schedule:")
        for i in model.C:
            for j in model.F:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0:  # Only print non-zero values
                    print(f"Cinema {i}, Film {j}: {x_val} screenings")
        
    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
cinema_optimization()