# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def phone_production_optimization():
    """Optimize phone production to minimize total cost while meeting hardware and accreditation requirements."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Chip models data
    chip_models_data = {
        1: {'cost': 50.0, 'RAM_MiB': 2048, 'ROM_MiB': 32768},
        2: {'cost': 75.0, 'RAM_MiB': 4096, 'ROM_MiB': 65536},
        3: {'cost': 100.0, 'RAM_MiB': 8192, 'ROM_MiB': 131072}
    }
    
    # Screen modes data
    screen_modes_data = {
        1: {'cost': 30.0, 'Accreditation_level': 3},
        2: {'cost': 45.0, 'Accreditation_level': 4},
        3: {'cost': 60.0, 'Accreditation_level': 5}
    }
    
    # Validate array lengths
    assert len(chip_models_data) == 3, "Chip models data length mismatch"
    assert len(screen_modes_data) == 3, "Screen modes data length mismatch"
    
    # 3. SETS
    model.ChipModels = pyo.Set(initialize=chip_models_data.keys())
    model.ScreenModes = pyo.Set(initialize=screen_modes_data.keys())
    
    # 4. PARAMETERS
    model.chip_cost = pyo.Param(model.ChipModels, initialize={i: chip_models_data[i]['cost'] for i in chip_models_data})
    model.chip_RAM = pyo.Param(model.ChipModels, initialize={i: chip_models_data[i]['RAM_MiB'] for i in chip_models_data})
    model.chip_ROM = pyo.Param(model.ChipModels, initialize={i: chip_models_data[i]['ROM_MiB'] for i in chip_models_data})
    
    model.screen_cost = pyo.Param(model.ScreenModes, initialize={j: screen_modes_data[j]['cost'] for j in screen_modes_data})
    model.screen_accred = pyo.Param(model.ScreenModes, initialize={j: screen_modes_data[j]['Accreditation_level'] for j in screen_modes_data})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.ChipModels, model.ScreenModes, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((model.chip_cost[i] + model.screen_cost[j]) * model.x[i, j] for i in model.ChipModels for j in model.ScreenModes)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    def ram_constraint_rule(model):
        return sum(model.chip_RAM[i] * model.x[i, j] for i in model.ChipModels for j in model.ScreenModes) >= 8000
    model.ram_constraint = pyo.Constraint(rule=ram_constraint_rule)
    
    def rom_constraint_rule(model):
        return sum(model.chip_ROM[i] * model.x[i, j] for i in model.ChipModels for j in model.ScreenModes) >= 128000
    model.rom_constraint = pyo.Constraint(rule=rom_constraint_rule)
    
    def accred_constraint_rule(model):
        return sum(model.screen_accred[j] * model.x[i, j] for i in model.ChipModels for j in model.ScreenModes) >= 5
    model.accred_constraint = pyo.Constraint(rule=accred_constraint_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nProduction quantities:")
        for i in model.ChipModels:
            for j in model.ScreenModes:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0:
                    print(f"Chip Model {i} with Screen Mode {j}: {int(x_val)} units")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

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