#!/usr/bin/env python3
"""
DOCplex 2.29.245 Implementation for Document Template Optimization
"""

from docplex.mp.model import Model

def optimize_template_allocation():
    """Optimize the allocation of document templates to minimize total cost."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="template_allocation")
    
    # Data from the problem
    template_ids = [1, 2, 3]
    document_ids = [101, 102, 103]
    
    # Costs and validity data
    template_costs = {1: 12.5, 2: 18.0, 3: 10.0}
    template_validity = {1: True, 2: False, 3: True}
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(template_ids) == len(template_costs) == len(template_validity), "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables: x[t, d] = 1 if template t is used for document d, else 0
    x = {(t, d): mdl.binary_var(name=f"x_{t}_{d}") for t in template_ids for d in document_ids}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of document creation
    objective = mdl.sum(template_costs[t] * x[t, d] for t in template_ids for d in document_ids)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Constraint 1: Single Template per Document
    for d in document_ids:
        mdl.add_constraint(mdl.sum(x[t, d] for t in template_ids) == 1, ctname=f"single_template_{d}")
    
    # Constraint 2: Template Validity
    for t in template_ids:
        for d in document_ids:
            mdl.add_constraint(x[t, d] <= int(template_validity[t]), ctname=f"validity_{t}_{d}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for t in template_ids:
            for d in document_ids:
                if solution.get_value(x[t, d]) > 0:
                    print(f"Template {t} is used for document {d}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    optimize_template_allocation()