# Complete PYOMO implementation - Retry Attempt 4

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

def farm_optimization():
    """Optimize farm participation in competitions to maximize wins."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    competitions = [1, 2, 3]
    farms = [101, 102, 103]
    win_coefficients_data = {
        (1, 101): 2.0,
        (2, 102): 1.5,
        (3, 103): 2.5,
        (1, 102): 1.2,
        (2, 103): 1.8
    }
    livestock_allocation_threshold = {
        101: 2,
        102: 2,
        103: 2
    }
    
    # CRITICAL: Validate data completeness
    assert all((i, j) in win_coefficients_data for i in competitions for j in farms if j in livestock_allocation_threshold), "Missing win coefficients"
    
    # 3. SETS
    model.Competitions = pyo.Set(initialize=competitions)
    model.Farms = pyo.Set(initialize=farms)
    
    # 4. PARAMETERS
    model.win_coefficient = pyo.Param(model.Competitions, model.Farms, initialize=win_coefficients_data, default=0)
    model.livestock_threshold = pyo.Param(model.Farms, initialize=livestock_allocation_threshold)
    
    # 5. VARIABLES
    model.is_participating = pyo.Var(model.Competitions, model.Farms, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def objective_rule(model):
        return sum(model.win_coefficient[i, j] * model.is_participating[i, j] for i in model.Competitions for j in model.Farms)
    model.objective = pyo.Objective(rule=objective_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def livestock_constraint_rule(model, j):
        return sum(model.is_participating[i, j] for i in model.Competitions) <= model.livestock_threshold[j]
    model.livestock_constraint = pyo.Constraint(model.Farms, rule=livestock_constraint_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("\nParticipation decisions:")
        for i in model.Competitions:
            for j in model.Farms:
                participation_val = pyo.value(model.is_participating[i, j])
                if participation_val > 0.5:  # Only print active participations
                    print(f"Competition {i}, Farm {j}: Participating")
        
    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
farm_optimization()