#!/usr/bin/env python3
"""
DOCplex 2.29.245 Cheat Sheet - Common Patterns & Syntax
Use as in-context example for LLM code generation
"""

from docplex.mp.model import Model

def optimization_example():
    """Essential DOCplex patterns - covers 90% of use cases"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="example")
    n_items = 5
    costs = [10, 15, 12, 8, 25]
    demands = [20, 30, 15, 40, 35]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(costs) == len(demands) == n_items, "Array length mismatch"
    safe_range = range(min(len(costs), len(demands)))  # Safe indexing
    
    # 2. VARIABLES
    # Single variables
    total = mdl.continuous_var(name="total", lb=0)
    
    # Variable dictionaries (most common)
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    y = {i: mdl.binary_var(name=f"y_{i}") for i in safe_range}
    z = {i: mdl.integer_var(name=f"z_{i}", lb=0, ub=10) for i in safe_range}
    
    # Variable collections using factory methods
    production = mdl.continuous_var_dict(safe_range, name="prod", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    # Use mdl.sum() for summations (DOCplex specific)
    objective = mdl.sum(costs[i] * x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Pattern A: Single constraint (RECOMMENDED)
    total_usage = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_usage <= 100, ctname="total_limit")
    
    # Pattern B: Individual constraints in loop with safe indexing
    for i in safe_range:
        mdl.add_constraint(x[i] <= demands[i] * y[i], ctname=f"link_{i}")
        mdl.add_constraint(x[i] >= 0.1 * demands[i], ctname=f"min_prod_{i}")
    
    # Pattern C: Batch constraints using generator expressions
    capacity_constraints = (x[i] + z[i] <= demands[i] for i in safe_range)
    mdl.add_constraints(capacity_constraints, names="capacity")
    
    # Pattern D: Range constraints (both bounds)
    for i in safe_range:
        mdl.add_range(0, x[i], demands[i], rname=f"bounds_{i}")
    
    # Pattern E: Equality constraints
    cost_expr = mdl.sum(costs[i] * x[i] for i in safe_range)
    mdl.add_constraint(total == cost_expr, ctname="total_def")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# SYNTAX RULES TO FOLLOW:
"""
CORRECT CONSTRAINT SYNTAX:
mdl.add_constraint(expr <= rhs, ctname="constraint_name")
mdl.add_constraint(expr >= rhs, ctname="constraint_name")
mdl.add_constraint(expr == rhs, ctname="constraint_name")

CORRECT SUMMATION:
mdl.sum(coef[i] * var[i] for i in safe_range)
mdl.sum(expr[i] for i in indices if condition)

ARRAY SAFETY (CRITICAL):
safe_range = range(min(len(array1), len(array2), len(array3)))
for i in safe_range: expr += array1[i] * var[i]

BATCH CONSTRAINTS:
constraints = (expr[i] <= rhs[i] for i in safe_range)
mdl.add_constraints(constraints, names="batch")

WRONG SYNTAX (causes IndexError):
for i in range(len(array1)): expr += array2[i] * var[i]  # If array2 shorter
mdl.sum(expr[i] for i in range(len(killed)))  # If other arrays shorter
sum(...)  # Use mdl.sum() instead
"""

# ARRAY SAFETY EXAMPLE:
def safe_indexing_example():
    """Shows how to prevent IndexError with different array lengths"""
    costs = [1, 2, 3, 4, 5]      # Length 5
    demands = [10, 20, 30]       # Length 3 (shorter!)
    capacities = [100, 200]      # Length 2 (shortest!)
    
    # WRONG: Will cause IndexError
    # for i in range(len(costs)): total += demands[i] * x[i]  # ERROR at i=3
    
    # CORRECT: Use safe range
    safe_len = min(len(costs), len(demands), len(capacities))
    safe_indices = range(safe_len)  # range(2) - safe for all arrays
    
    mdl = Model("safe_example")
    x = {i: mdl.continuous_var(name=f"x_{i}") for i in safe_indices}
    
    # Now safe to use all arrays with safe_indices
    obj = mdl.sum(costs[i] * x[i] for i in safe_indices)
    mdl.minimize(obj)
    
    for i in safe_indices:
        mdl.add_constraint(x[i] <= capacities[i], ctname=f"cap_{i}")
        mdl.add_constraint(x[i] >= 0.1 * demands[i], ctname=f"dem_{i}")
    
    return mdl

