#!/usr/bin/env python3
"""
DOCplex implementation for theme gallery optimization problem
"""

from docplex.mp.model import Model

def theme_gallery_optimization():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="theme_gallery_optimization")
    
    # Data from the provided SQL inserts
    artist_ids = [1, 2, 3]
    exhibition_ids = [1, 2, 3]
    
    # Artist availability constraints
    max_exhibitions = {1: 5, 2: 6, 3: 4}
    
    # Exhibition requirements
    min_artists = {1: 3, 2: 4, 3: 3}
    
    # Ticket prices
    ticket_prices = {1: 50, 2: 70, 3: 60}
    
    # Attendance data
    attendance = {
        (1, 1): 100,
        (2, 2): 200,
        (3, 3): 150
    }
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(artist_ids) == len(max_exhibitions), "Artist data length mismatch"
    assert len(exhibition_ids) == len(min_artists) == len(ticket_prices), "Exhibition data length mismatch"
    
    # 2. VARIABLES
    # Decision variables: x_ij = number of exhibitions artist i participates in at exhibition j
    x = {(i, j): mdl.integer_var(name=f"x_{i}_{j}", lb=0) for i in artist_ids for j in exhibition_ids}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total annual revenue
    revenue = mdl.sum(ticket_prices[j] * attendance[(i, j)] * x[(i, j)] for i in artist_ids for j in exhibition_ids if (i, j) in attendance)
    mdl.maximize(revenue)
    
    # 4. CONSTRAINTS
    
    # Artist Availability Constraint
    for i in artist_ids:
        total_exhibitions = mdl.sum(x[(i, j)] for j in exhibition_ids if (i, j) in x)
        mdl.add_constraint(total_exhibitions <= max_exhibitions[i], ctname=f"artist_availability_{i}")
    
    # Exhibition Requirement Constraint
    for j in exhibition_ids:
        total_artists = mdl.sum(x[(i, j)] for i in artist_ids if (i, j) in x)
        mdl.add_constraint(total_artists >= min_artists[j], ctname=f"exhibition_requirement_{j}")
    
    # Non-Negativity Constraint is already handled by the variable definition (lb=0)
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in artist_ids:
            for j in exhibition_ids:
                if (i, j) in x:
                    value = solution.get_value(x[(i, j)])
                    if value > 1e-6:
                        print(f"x[{i},{j}] = {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
if __name__ == "__main__":
    theme_gallery_optimization()