# Complete PYOMO implementation

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

def machine_repair_optimization():
    """Optimize technician assignments to minimize machine repair value points"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided database schema and current stored values
    machines = [1, 2, 3]
    technicians = [1, 2, 3]
    value_points = {1: 15, 2: 25, 3: 10}
    max_repairs = {1: 3, 2: 2, 3: 1}
    
    # CRITICAL: Validate data lengths before indexing
    assert len(machines) == len(value_points), "Mismatch in machines and value points data"
    assert len(technicians) == len(max_repairs), "Mismatch in technicians and max repairs data"
    
    # 3. SETS
    model.M = pyo.Set(initialize=machines)  # Machines
    model.T = pyo.Set(initialize=technicians)  # Technicians
    
    # 4. PARAMETERS
    model.value_points = pyo.Param(model.M, initialize=value_points)
    model.max_repairs = pyo.Param(model.T, initialize=max_repairs)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.T, model.M, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.value_points[m] * model.x[t, m] for t in model.T for m in model.M)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Each repair must be assigned to exactly one technician
    def repair_assignment_rule(model, m):
        return sum(model.x[t, m] for t in model.T) == 1
    model.repair_assignment_constraint = pyo.Constraint(model.M, rule=repair_assignment_rule)
    
    # Technician capacity constraints
    def technician_capacity_rule(model, t):
        return sum(model.x[t, m] for m in model.M) <= model.max_repairs[t]
    model.technician_capacity_constraint = pyo.Constraint(model.T, rule=technician_capacity_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("\nAssignment of technicians to repairs:")
        for t in model.T:
            for m in model.M:
                if pyo.value(model.x[t, m]) > 0.5:  # Binary variable, check if assigned
                    print(f"Technician {t} assigned to machine {m}")
        
    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
machine_repair_optimization()