# Complete PYOMO implementation

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

def wedding_optimization():
    """Optimize the allocation of weddings to churches"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Example data based on the provided schema and realistic data
    church_ids = [1, 2, 3]
    male_ids = [101, 102, 103]
    female_ids = [201, 202, 203]
    capacities = {1: 100, 2: 150, 3: 200}

    # 3. SETS
    model.I = pyo.Set(initialize=church_ids)
    model.J = pyo.Set(initialize=male_ids)
    model.K = pyo.Set(initialize=female_ids)

    # 4. PARAMETERS
    model.capacity = pyo.Param(model.I, initialize=capacities)

    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, model.K, within=pyo.Binary)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[i, j, k] for i in model.I for j in model.J for k in model.K)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)

    # 7. CONSTRAINTS

    # Church Capacity Constraints
    def church_capacity_rule(model, i):
        return sum(model.x[i, j, k] for j in model.J for k in model.K) <= model.capacity[i]
    model.church_capacity_constraint = pyo.Constraint(model.I, rule=church_capacity_rule)

    # Unique Male Participation
    def unique_male_rule(model, j):
        return sum(model.x[i, j, k] for i in model.I for k in model.K) <= 1
    model.unique_male_constraint = pyo.Constraint(model.J, rule=unique_male_rule)

    # Unique Female Participation
    def unique_female_rule(model, k):
        return sum(model.x[i, j, k] for i in model.I for j in model.J) <= 1
    model.unique_female_constraint = pyo.Constraint(model.K, rule=unique_female_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)

    # 9. RESULT PROCESSING
    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:
            for j in model.J:
                for k in model.K:
                    x_val = pyo.value(model.x[i, j, k])
                    if x_val > 1e-6:  # Only print non-zero values
                        print(f"x[{i},{j},{k}] = {int(x_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

# Run the optimization
wedding_optimization()