#!/usr/bin/env python3
"""
DOCPLEX implementation for book production optimization problem
"""

from docplex.mp.model import Model

def book_production_optimization():
    """Optimize book production to maximize revenue within constraints"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="book_production_optimization")
    
    # Data from the problem description
    book_prices = [20.0, 25.0, 30.0]
    production_costs = [10.0, 12.0, 15.0]
    min_demands = [500, 600, 700]
    max_issues = [6000, 6000, 6000]
    total_budget = 150000
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(book_prices) == len(production_costs) == len(min_demands) == len(max_issues), "Array length mismatch"
    safe_range = range(min(len(book_prices), len(production_costs), len(min_demands), len(max_issues)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: number of copies produced for each book
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    revenue = mdl.sum(book_prices[i] * x[i] for i in safe_range)
    mdl.maximize(revenue)
    
    # 4. CONSTRAINTS
    
    # Total Production Budget
    total_cost = mdl.sum(production_costs[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_cost <= total_budget, ctname="total_budget")
    
    # Maximum Issues per Book
    for i in safe_range:
        mdl.add_constraint(x[i] <= max_issues[i], ctname=f"max_issues_{i}")
    
    # Minimum Demand
    for i in safe_range:
        mdl.add_constraint(x[i] >= min_demands[i], ctname=f"min_demand_{i}")
    
    # 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])
            print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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