# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_phone_production(total_ram, total_rom, total_screen):
    """Optimize phone production to maximize profit given resource constraints."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="phone_production")
    
    # Data from the problem context
    model_ids = [1, 2, 3]
    ram_requirements = [4, 8, 16]
    rom_requirements = [16, 32, 64]
    screen_requirements = [1, 2, 3]
    profit_per_unit = [50.0, 75.0, 100.0]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(model_ids) == len(ram_requirements) == len(rom_requirements) == len(screen_requirements) == len(profit_per_unit), "Array length mismatch"
    safe_range = range(len(model_ids))  # Safe indexing
    
    # 2. VARIABLES
    units_produced = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total profit
    total_profit = mdl.sum(profit_per_unit[i] * units_produced[i] for i in safe_range)
    mdl.maximize(total_profit)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # RAM Constraint
    total_ram_usage = mdl.sum(ram_requirements[i] * units_produced[i] for i in safe_range)
    mdl.add_constraint(total_ram_usage <= total_ram, ctname="ram_constraint")
    
    # ROM Constraint
    total_rom_usage = mdl.sum(rom_requirements[i] * units_produced[i] for i in safe_range)
    mdl.add_constraint(total_rom_usage <= total_rom, ctname="rom_constraint")
    
    # Screen Constraint
    total_screen_usage = mdl.sum(screen_requirements[i] * units_produced[i] for i in safe_range)
    mdl.add_constraint(total_screen_usage <= total_screen, ctname="screen_constraint")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(units_produced[i])
            if value > 1e-6:
                print(f"Units produced for model {model_ids[i]}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Example usage with total available resources
optimize_phone_production(total_ram=10000, total_rom=20000, total_screen=5000)