#!/usr/bin/env python3
"""
DOCplex implementation for workshop paper selection optimization
"""

from docplex.mp.model import Model

def workshop_paper_optimization():
    """Optimize the selection of workshop submissions to maximize quality scores"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="workshop_paper_selection")
    
    # Data from the database
    workshop_capacity = {1: 12, 2: 15, 3: 10}
    submission_scores = {1: 8.7, 2: 7.5, 3: 9.2}
    submission_workshop_mapping = {1: 1, 2: 2, 3: 3}
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(submission_scores) == len(submission_workshop_mapping), "Array length mismatch"
    safe_range = range(min(len(submission_scores), len(submission_workshop_mapping)))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for each submission
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total quality score of accepted submissions
    objective = mdl.sum(submission_scores[i+1] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Workshop Capacity Constraints
    # Group submissions by workshop
    workshop_submissions = {j: [i for i in safe_range if submission_workshop_mapping[i+1] == j] for j in workshop_capacity}
    
    for j, submissions in workshop_submissions.items():
        mdl.add_constraint(mdl.sum(x[i] for i in submissions) <= workshop_capacity[j], ctname=f"workshop_capacity_{j}")
    
    # Binary Decision Constraints are inherently handled by the binary_var type
    
    # 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+1}] = {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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