#!/usr/bin/env python3
"""
DOCplex implementation for farm selection optimization problem
"""

from docplex.mp.model import Model

def farm_selection_optimization():
    """Optimize farm selection to maximize quality score while respecting city constraints"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="farm_selection")
    
    # Data from the problem
    farm_ids = [1, 2, 3]
    horses = [5, 10, 15]
    cattle = [20, 30, 40]
    pigs = [50, 60, 70]
    sheep_and_goats = [30, 40, 50]
    
    # City capacities
    max_farms = 10
    max_horses = 50
    max_cattle = 100
    max_pigs = 200
    max_sheep_goats = 150
    
    # Weights for quality score calculation
    horse_weight = 0.30
    cattle_weight = 0.25
    pig_weight = 0.20
    sheep_goat_weight = 0.25
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(farm_ids) == len(horses) == len(cattle) == len(pigs) == len(sheep_and_goats), "Array length mismatch"
    safe_range = range(min(len(farm_ids), len(horses), len(cattle), len(pigs), len(sheep_and_goats)))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.binary_var(name=f"x_{farm_ids[i]}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Quality score calculation
    quality_score = mdl.sum(
        (horse_weight * horses[i] + cattle_weight * cattle[i] + pig_weight * pigs[i] + sheep_goat_weight * sheep_and_goats[i]) * x[i]
        for i in safe_range
    )
    mdl.maximize(quality_score)
    
    # 4. CONSTRAINTS
    
    # Maximum number of farms
    mdl.add_constraint(mdl.sum(x[i] for i in safe_range) <= max_farms, ctname="max_farms")
    
    # Maximum number of horses
    mdl.add_constraint(mdl.sum(horses[i] * x[i] for i in safe_range) <= max_horses, ctname="max_horses")
    
    # Maximum number of cattle
    mdl.add_constraint(mdl.sum(cattle[i] * x[i] for i in safe_range) <= max_cattle, ctname="max_cattle")
    
    # Maximum number of pigs
    mdl.add_constraint(mdl.sum(pigs[i] * x[i] for i in safe_range) <= max_pigs, ctname="max_pigs")
    
    # Maximum number of sheep and goats
    mdl.add_constraint(mdl.sum(sheep_and_goats[i] * x[i] for i in safe_range) <= max_sheep_goats, ctname="max_sheep_goats")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"Farm {farm_ids[i]} is invited: {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    farm_selection_optimization()