# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def dorm_assignment_optimization():
    """DOCplex implementation for dorm assignment optimization problem"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="dorm_assignment")
    
    # Example data setup (replace with actual data retrieval logic)
    students = [1, 2, 3]
    dorms = [101, 102, 103]
    capacities = {101: 1, 102: 1, 103: 1}
    gender_match = {(1, 101): 1, (2, 102): 1, (3, 103): 1}
    
    # Objective coefficients from the database
    coefficients = {
        (1, 101): 1.0,
        (2, 102): 1.0,
        (3, 103): 0.5
    }
    
    # CRITICAL: Validate data consistency
    assert all((i, j) in coefficients for i in students for j in dorms), "Coefficient data missing"
    
    # 2. VARIABLES
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in students for j in dorms}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(coefficients[i, j] * x[i, j] for i in students for j in dorms)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Capacity constraints
    for j in dorms:
        mdl.add_constraint(mdl.sum(x[i, j] for i in students) <= capacities[j], ctname=f"capacity_{j}")
    
    # Gender compatibility constraints
    for i in students:
        for j in dorms:
            mdl.add_constraint(x[i, j] <= gender_match.get((i, j), 0), ctname=f"gender_match_{i}_{j}")
    
    # Assignment constraints
    for i in students:
        mdl.add_constraint(mdl.sum(x[i, j] for j in dorms) == 1, ctname=f"assignment_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in students:
            for j in dorms:
                if solution.get_value(x[i, j]) > 0.5:  # Binary variable threshold
                    print(f"Student {i} assigned to Dorm {j}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

# Run the optimization
dorm_assignment_optimization()