# Complete PYOMO implementation

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

def party_host_optimization():
    """Optimize host assignments to parties"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data setup
    parties = [1, 2, 3]
    hosts = [101, 102, 103, 104, 105]
    max_hosts_per_party = 2
    
    # CRITICAL: Validate array lengths before indexing
    assert len(parties) > 0 and len(hosts) > 0, "Parties or hosts list is empty"
    
    # 3. SETS
    model.I = pyo.Set(initialize=parties)
    model.J = pyo.Set(initialize=hosts)
    
    # 4. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 5. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 6. CONSTRAINTS
    
    # Each party must have at least one host
    def min_host_rule(model, i):
        return sum(model.x[i, j] for j in model.J) >= 1
    model.min_host_constraint = pyo.Constraint(model.I, rule=min_host_rule)
    
    # No party should exceed the maximum number of hosts allowed
    def max_host_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= max_hosts_per_party
    model.max_host_constraint = pyo.Constraint(model.I, rule=max_host_rule)
    
    # 7. 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
    
    # 8. 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("\nHost assignments:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assigned hosts
                    print(f"Party {i} is assigned Host {j}")
        
    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
party_host_optimization()