#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Cinema Scheduling Optimization
"""

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

def cinema_scheduling_optimization():
    """Optimize cinema scheduling to maximize revenue"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Films data (Price, Show_times_per_day)
    films_data = [
        (12.99, 3),
        (9.99, 2),
        (7.99, 1)
    ]
    
    # Cinemas data (Capacity)
    cinemas_data = [150, 200, 100]
    
    # Maximum showings per day per cinema
    max_showings_per_day = 12
    
    # Validate array lengths
    assert len(films_data) > 0, "No films data provided"
    assert len(cinemas_data) > 0, "No cinemas data provided"
    
    # 3. SETS
    model.F = pyo.RangeSet(1, len(films_data))  # Films set
    model.C = pyo.RangeSet(1, len(cinemas_data))  # Cinemas set
    
    # 4. PARAMETERS
    # Price per showing for each film
    model.price = pyo.Param(model.F, initialize={i+1: films_data[i][0] for i in range(len(films_data))})
    
    # Capacity of each cinema
    model.capacity = pyo.Param(model.C, initialize={i+1: cinemas_data[i-1] for i in model.C})
    
    # 5. VARIABLES
    # Number of showings per day for film f in cinema c
    model.x = pyo.Var(model.F, model.C, within=pyo.NonNegativeIntegers, bounds=(1, max_showings_per_day))
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total revenue
    def obj_rule(model):
        return sum(model.price[f] * model.capacity[c] * model.x[f, c] for f in model.F for c in model.C)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Maximum showings per day per cinema
    def max_showings_rule(model, c):
        return sum(model.x[f, c] for f in model.F) <= max_showings_per_day
    model.max_showings_constraint = pyo.Constraint(model.C, rule=max_showings_rule)
    
    # Total capacity per day
    def total_capacity_rule(model, c):
        return sum(model.capacity[c] * model.x[f, c] for f in model.F) <= model.capacity[c] * max_showings_per_day
    model.total_capacity_constraint = pyo.Constraint(model.C, rule=total_capacity_rule)
    
    # Minimum showings per film
    def min_showings_rule(model, f, c):
        return model.x[f, c] >= 1
    model.min_showings_constraint = pyo.Constraint(model.F, model.C, rule=min_showings_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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nNumber of showings per film per cinema:")
        for f in model.F:
            for c in model.C:
                x_val = pyo.value(model.x[f, c])
                print(f"Film {f} in Cinema {c}: {x_val} showings")
        
    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
if __name__ == "__main__":
    cinema_scheduling_optimization()