#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Coffee Shop Staff Allocation Optimization
"""

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

def coffee_shop_optimization():
    """Optimize staff allocation for coffee shop happy hours"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    shops = [1, 2, 3]  # Shop indices
    membership_levels = {1: 1, 2: 2, 3: 3}  # Membership levels for each shop
    spending_per_member = {1: 25.5, 2: 30.0, 3: 15.75}  # Spending per member for each shop
    min_staff = {1: 2, 2: 3, 3: 4}  # Minimum staff per shop
    max_staff = {1: 10, 2: 12, 3: 15}  # Maximum staff per shop
    total_staff_budget = 150  # Total staff budget across all shops
    max_spending_per_member = 50  # Maximum spending per member
    
    # CRITICAL: Validate array lengths before indexing
    assert len(shops) == len(membership_levels) == len(spending_per_member) == len(min_staff) == len(max_staff), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=shops)  # Set of shops
    
    # 4. PARAMETERS (data containers)
    model.membership_level = pyo.Param(model.I, initialize=membership_levels)
    model.spending_per_member = pyo.Param(model.I, initialize=spending_per_member)
    model.min_staff = pyo.Param(model.I, initialize=min_staff)
    model.max_staff = pyo.Param(model.I, initialize=max_staff)
    model.total_staff_budget = pyo.Param(initialize=total_staff_budget)
    model.max_spending_per_member = pyo.Param(initialize=max_spending_per_member)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)  # Number of staff per shop
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.membership_level[i] * model.spending_per_member[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total Staff Budget Constraint
    def total_staff_budget_rule(model):
        return sum(model.x[i] for i in model.I) <= model.total_staff_budget
    model.total_staff_budget_constraint = pyo.Constraint(rule=total_staff_budget_rule)
    
    # Shop Staffing Limits
    def shop_staffing_limits_rule(model, i):
        return (model.min_staff[i], model.x[i], model.max_staff[i])
    model.shop_staffing_limits_constraint = pyo.Constraint(model.I, rule=shop_staffing_limits_rule)
    
    # Maximum Spending Limit per Member
    def max_spending_limit_rule(model, i):
        return model.spending_per_member[i] <= model.max_spending_per_member
    model.max_spending_limit_constraint = pyo.Constraint(model.I, rule=max_spending_limit_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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nStaff allocation per shop:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"Shop {i}: {int(x_val)} staff")
        
    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__":
    coffee_shop_optimization()