# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_template_assignment():
    """Optimize the assignment of templates to documents to minimize total cost."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="TemplateAssignment")
    
    # Data from the problem context
    template_ids = [1, 2, 3]
    document_ids = [101, 102, 103]
    costs = [50.0, 75.0, 100.0]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(template_ids) == len(costs), "Array length mismatch"
    safe_range_templates = range(len(template_ids))
    safe_range_documents = range(len(document_ids))
    
    # 2. VARIABLES
    # Binary variables for document-template assignment
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_range_documents for j in safe_range_templates}
    
    # Binary variables for template usage
    y = {j: mdl.binary_var(name=f"y_{j}") for j in safe_range_templates}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of templates used
    objective = mdl.sum(costs[j] * y[j] for j in safe_range_templates)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Constraint 1: Each document is assigned to exactly one template
    for i in safe_range_documents:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_range_templates) == 1, ctname=f"assign_doc_{i}")
    
    # Constraint 2: Link template usage to document assignment
    for i in safe_range_documents:
        for j in safe_range_templates:
            mdl.add_constraint(x[i, j] <= y[j], ctname=f"link_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for j in safe_range_templates:
            if solution.get_value(y[j]) > 0.5:  # Template is used
                print(f"Template {template_ids[j]} is used.")
        for i in safe_range_documents:
            for j in safe_range_templates:
                if solution.get_value(x[i, j]) > 0.5:
                    print(f"Document {document_ids[i]} is assigned to Template {template_ids[j]}.")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_template_assignment()