# Complete PYOMO implementation

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

def wedding_optimization():
    """Optimize the number of weddings to minimize total cost while respecting constraints."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    churches = [1, 2, 3]
    years = [2023, 2024]
    
    # Cost per wedding data
    cost_data = {
        (1, 2023): 5000.0,
        (2, 2023): 4500.0,
        (3, 2023): 6000.0,
        (1, 2024): 5200.0,
        (2, 2024): 4600.0,
        (3, 2024): 6100.0
    }
    
    # Validate data lengths
    assert len(cost_data) == len(churches) * len(years), "Cost data length mismatch"
    
    # 3. SETS
    model.C = pyo.Set(initialize=churches)  # Churches
    model.Y = pyo.Set(initialize=years)    # Years
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.C, model.Y, initialize=cost_data)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.C, model.Y, within=pyo.NonNegativeIntegers, bounds=(0, 30))
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[c, y] * model.x[c, y] for c in model.C for y in model.Y)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Annual Wedding Limit
    def annual_limit_rule(model, y):
        return sum(model.x[c, y] for c in model.C) <= 120
    model.annual_limit = pyo.Constraint(model.Y, rule=annual_limit_rule)
    
    # Church Capacity Limit (already enforced by variable bounds)
    
    # 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 c in model.C:
            for y in model.Y:
                x_val = pyo.value(model.x[c, y])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{c}, {y}] = {x_val:.0f}")
        
    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__":
    wedding_optimization()