#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Party People Optimization Problem
"""

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

def party_people_optimization():
    """Optimize member and event allocation to maximize influence across regions."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    regions = [1, 2, 3]
    influence_coefficients = {1: 0.6, 2: 0.7, 3: 0.5}
    total_members_available = {1: 20, 2: 25, 3: 15}
    max_events = {1: 5, 2: 6, 3: 4}
    min_members = {1: 5, 2: 6, 3: 4}
    min_events = {1: 1, 2: 2, 3: 1}
    cost_per_event = 6000
    total_budget = 150000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(regions) == len(influence_coefficients) == len(total_members_available) == len(max_events) == len(min_members) == len(min_events), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=regions)
    
    # 4. PARAMETERS (data containers)
    model.influence_coefficient = pyo.Param(model.I, initialize=influence_coefficients)
    model.total_members_available = pyo.Param(model.I, initialize=total_members_available)
    model.max_events = pyo.Param(model.I, initialize=max_events)
    model.min_members = pyo.Param(model.I, initialize=min_members)
    model.min_events = pyo.Param(model.I, initialize=min_events)
    model.cost_per_event = pyo.Param(initialize=cost_per_event)
    model.total_budget = pyo.Param(initialize=total_budget)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)  # Number of members assigned
    model.y = pyo.Var(model.I, within=pyo.NonNegativeIntegers)  # Number of events organized
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.influence_coefficient[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Budget Constraint
    def budget_rule(model):
        return sum(model.cost_per_event * model.y[i] for i in model.I) <= model.total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Member Assignment Upper Bound
    def member_upper_rule(model, i):
        return model.x[i] <= model.total_members_available[i]
    model.member_upper_constraint = pyo.Constraint(model.I, rule=member_upper_rule)
    
    # Member Assignment Lower Bound
    def member_lower_rule(model, i):
        return model.x[i] >= model.min_members[i]
    model.member_lower_constraint = pyo.Constraint(model.I, rule=member_lower_rule)
    
    # Event Organization Upper Bound
    def event_upper_rule(model, i):
        return model.y[i] <= model.max_events[i]
    model.event_upper_constraint = pyo.Constraint(model.I, rule=event_upper_rule)
    
    # Event Organization Lower Bound
    def event_lower_rule(model, i):
        return model.y[i] >= model.min_events[i]
    model.event_lower_constraint = pyo.Constraint(model.I, rule=event_lower_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 in model.I:
            x_val = pyo.value(model.x[i])
            y_val = pyo.value(model.y[i])
            print(f"Region {i}: Members = {int(x_val)}, Events = {int(y_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

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