# Complete PYOMO implementation

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

def template_optimization():
    """Optimize template allocation for document creation."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    templates = [1, 2, 3]
    documents = [101, 102, 103]
    
    # Template costs
    template_costs = {1: 12.5, 2: 18.0, 3: 10.0}
    
    # Template validity
    template_validity = {1: 1, 2: 0, 3: 1}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(template_costs) == len(template_validity) == len(templates), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.T = pyo.Set(initialize=templates)  # Set of templates
    model.D = pyo.Set(initialize=documents)  # Set of documents
    
    # 4. PARAMETERS (data containers)
    model.cost = pyo.Param(model.T, initialize=template_costs)
    model.valid = pyo.Param(model.T, initialize=template_validity)
    
    # 5. VARIABLES
    # Binary decision variable: x[t, d] = 1 if template t is used for document d
    model.x = pyo.Var(model.T, model.D, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Minimize the total cost of document creation
    def obj_rule(model):
        return sum(model.cost[t] * model.x[t, d] for t in model.T for d in model.D)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Constraint 1: Each document must use exactly one template
    def single_template_rule(model, d):
        return sum(model.x[t, d] for t in model.T) == 1
    model.single_template_constraint = pyo.Constraint(model.D, rule=single_template_rule)
    
    # Constraint 2: A template can only be used if it is valid
    def validity_rule(model, t, d):
        return model.x[t, d] <= model.valid[t]
    model.validity_constraint = pyo.Constraint(model.T, model.D, rule=validity_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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("\nVariable values:")
        for t in model.T:
            for d in model.D:
                x_val = pyo.value(model.x[t, d])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{t}, {d}] = {int(x_val)}")
        
    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__":
    template_optimization()