# Complete PYOMO implementation

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

def cre_Doc_Template_Mgt():
    """Optimization for minimizing template costs in document assignment"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define the data based on the provided database schema and current stored values
    template_ids = [1, 2, 3]
    document_ids = [101, 102, 103]
    costs = {1: 50.0, 2: 75.0, 3: 100.0}
    
    # Validate data lengths
    assert len(template_ids) == len(costs), "Mismatch in template data lengths"
    
    # 3. SETS
    model.Templates = pyo.Set(initialize=template_ids)
    model.Documents = pyo.Set(initialize=document_ids)
    
    # 4. PARAMETERS
    model.Cost = pyo.Param(model.Templates, initialize=costs)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Documents, model.Templates, within=pyo.Binary)
    model.y = pyo.Var(model.Templates, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Cost[j] * model.y[j] for j in model.Templates)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Each document is assigned to exactly one template
    def assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.Templates) == 1
    model.assignment_constraint = pyo.Constraint(model.Documents, rule=assignment_rule)
    
    # Link template usage to document assignment
    def linking_rule(model, i, j):
        return model.x[i, j] <= model.y[j]
    model.linking_constraint = pyo.Constraint(model.Documents, model.Templates, rule=linking_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("\nVariable values:")
        for i in model.Documents:
            for j in model.Templates:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i},{j}] = {int(x_val)}")
        
        for j in model.Templates:
            y_val = pyo.value(model.y[j])
            print(f"y[{j}] = {int(y_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

# Run the optimization
cre_Doc_Template_Mgt()