# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_book_publication():
    """Optimize the number of issues to publish for each book to maximize revenue."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="book_publication")
    
    # Prices from the publication table
    prices = [18.99, 22.5, 14.75]
    
    # Maximum number of issues allowed and total budget available
    max_issues = 50  # Example value for maximum number of issues
    total_budget = 1000  # Example value for total budget
    
    # CRITICAL: Validate array lengths to prevent IndexError
    n_books = len(prices)
    safe_range = range(n_books)  # Safe indexing
    
    # 2. VARIABLES
    # Integer variables for the number of issues to publish for each book
    issues = {i: mdl.integer_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    revenue = mdl.sum(prices[i] * issues[i] for i in safe_range)
    mdl.maximize(revenue)
    
    # 4. CONSTRAINTS
    # Total number of issues constraint
    total_issues = mdl.sum(issues[i] for i in safe_range)
    mdl.add_constraint(total_issues <= max_issues, ctname="total_issues_limit")
    
    # Budget constraint
    total_cost = mdl.sum(prices[i] * issues[i] for i in safe_range)
    mdl.add_constraint(total_cost <= total_budget, ctname="budget_limit")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(issues[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_book_publication()