#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Farm Selection Optimization Problem
"""

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

def farm_selection_optimization():
    """Optimization model to select farms for the competition"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Farm data
    farms_data = {
        1: {'horses': 5, 'cattle': 20, 'pigs': 50, 'sheep_and_goats': 30},
        2: {'horses': 10, 'cattle': 30, 'pigs': 60, 'sheep_and_goats': 40},
        3: {'horses': 15, 'cattle': 40, 'pigs': 70, 'sheep_and_goats': 50}
    }
    
    # City capacities
    city_capacities = {
        'max_farms': 10,
        'max_horses': 50,
        'max_cattle': 100,
        'max_pigs': 200,
        'max_sheep_goats': 150
    }
    
    # Validate data lengths
    assert len(farms_data) == 3, "Farm data length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=farms_data.keys())  # Set of farms
    
    # 4. PARAMETERS
    model.horses = pyo.Param(model.I, initialize={i: farms_data[i]['horses'] for i in model.I})
    model.cattle = pyo.Param(model.I, initialize={i: farms_data[i]['cattle'] for i in model.I})
    model.pigs = pyo.Param(model.I, initialize={i: farms_data[i]['pigs'] for i in model.I})
    model.sheep_and_goats = pyo.Param(model.I, initialize={i: farms_data[i]['sheep_and_goats'] for i in model.I})
    
    model.max_farms = pyo.Param(initialize=city_capacities['max_farms'])
    model.max_horses = pyo.Param(initialize=city_capacities['max_horses'])
    model.max_cattle = pyo.Param(initialize=city_capacities['max_cattle'])
    model.max_pigs = pyo.Param(initialize=city_capacities['max_pigs'])
    model.max_sheep_goats = pyo.Param(initialize=city_capacities['max_sheep_goats'])
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)  # Binary decision variable for farm selection
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(24 * model.x[1] + 32.5 * model.x[2] + 41 * model.x[3])
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def max_farms_rule(model):
        return sum(model.x[i] for i in model.I) <= model.max_farms
    model.max_farms_constraint = pyo.Constraint(rule=max_farms_rule)
    
    def max_horses_rule(model):
        return sum(model.horses[i] * model.x[i] for i in model.I) <= model.max_horses
    model.max_horses_constraint = pyo.Constraint(rule=max_horses_rule)
    
    def max_cattle_rule(model):
        return sum(model.cattle[i] * model.x[i] for i in model.I) <= model.max_cattle
    model.max_cattle_constraint = pyo.Constraint(rule=max_cattle_rule)
    
    def max_pigs_rule(model):
        return sum(model.pigs[i] * model.x[i] for i in model.I) <= model.max_pigs
    model.max_pigs_constraint = pyo.Constraint(rule=max_pigs_rule)
    
    def max_sheep_goats_rule(model):
        return sum(model.sheep_and_goats[i] * model.x[i] for i in model.I) <= model.max_sheep_goats
    model.max_sheep_goats_constraint = pyo.Constraint(rule=max_sheep_goats_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("\nSelected farms:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected farms
                print(f"Farm {i} is selected")
        
    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__":
    farm_selection_optimization()