# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def farm_optimization():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="farm_optimization")
    
    # Data setup
    competitions = [1, 2, 3]
    farms = [101, 102, 103]
    
    # Win coefficients data
    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 thresholds (assumed known)
    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), "Missing win coefficients"
    
    # Safe range for indexing
    safe_competitions = range(len(competitions))
    safe_farms = range(len(farms))
    
    # 2. VARIABLES
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in competitions for j in farms}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(win_coefficients_data[(i, j)] * x[(i, j)] for i in competitions for j in farms)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Livestock allocation constraint
    for j in farms:
        mdl.add_constraint(mdl.sum(x[(i, j)] for i in competitions) <= livestock_allocation_threshold[j], ctname=f"livestock_limit_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in competitions:
            for j in farms:
                value = solution.get_value(x[(i, j)])
                if value > 1e-6:
                    print(f"x[{i},{j}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

# Execute the optimization
farm_optimization()