#!/usr/bin/env python3
"""
DOCplex implementation for museum ticket sales optimization
"""

from docplex.mp.model import Model

def museum_optimization():
    """Optimize museum ticket sales to maximize revenue"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="museum_visit")
    
    # Data from the problem
    museum_ids = [1, 2, 3]
    total_ticket_limits = [1200, 1500, 1000]
    staff_capacities = [600, 750, 500]
    total_spent = [2500.0, 3500.0, 1500.0]
    num_of_tickets = [500, 700, 300]
    
    # Calculate revenue per ticket
    revenue_per_ticket = [total_spent[i] / num_of_tickets[i] for i in range(len(museum_ids))]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(museum_ids) == len(total_ticket_limits) == len(staff_capacities) == len(revenue_per_ticket), "Array length mismatch"
    safe_range = range(min(len(museum_ids), len(total_ticket_limits), len(staff_capacities), len(revenue_per_ticket)))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.continuous_var(name=f"x_{museum_ids[i]}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(revenue_per_ticket[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Ticket Sales Limit
    for i in safe_range:
        mdl.add_constraint(x[i] <= total_ticket_limits[i], ctname=f"ticket_limit_{museum_ids[i]}")
    
    # Staff Availability
    for i in safe_range:
        mdl.add_constraint(x[i] <= staff_capacities[i], ctname=f"staff_capacity_{museum_ids[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"Tickets sold at museum {museum_ids[i]}: {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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