#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Museum Revenue Optimization
"""

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

def museum_revenue_optimization():
    """Optimize museum ticket sales to maximize revenue."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    museums = [1, 2, 3]
    total_ticket_limit = {1: 1200, 2: 1500, 3: 1000}
    staff_capacity = {1: 600, 2: 750, 3: 500}
    revenue_per_ticket = {1: 5.0, 2: 5.0, 3: 5.0}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(museums) == len(total_ticket_limit) == len(staff_capacity) == len(revenue_per_ticket), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=museums)
    
    # 4. PARAMETERS (data containers)
    model.total_ticket_limit = pyo.Param(model.I, initialize=total_ticket_limit)
    model.staff_capacity = pyo.Param(model.I, initialize=staff_capacity)
    model.revenue_per_ticket = pyo.Param(model.I, initialize=revenue_per_ticket)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.revenue_per_ticket[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def ticket_limit_rule(model, i):
        return model.x[i] <= model.total_ticket_limit[i]
    model.ticket_limit_constraint = pyo.Constraint(model.I, rule=ticket_limit_rule)
    
    def staff_capacity_rule(model, i):
        return model.x[i] <= model.staff_capacity[i]
    model.staff_capacity_constraint = pyo.Constraint(model.I, rule=staff_capacity_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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("\nOptimal ticket sales:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"Museum {i}: {x_val:.0f} tickets")
        
    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

# Execute the optimization
if __name__ == "__main__":
    museum_revenue_optimization()