# Complete PYOMO implementation

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

def phone_optimization():
    """Optimize phone production for maximum profit"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Data from the problem statement
    n_models = 3
    profits = [50.0, 75.0, 100.0]
    ram_requirements = [4, 8, 16]
    rom_requirements = [16, 32, 64]
    screen_requirements = [1, 2, 3]
    
    # Total available resources
    total_ram = 10000  # Example value
    total_rom = 20000  # Example value
    total_screen = 5000  # Example value

    # CRITICAL: Validate array lengths before indexing
    assert len(profits) == len(ram_requirements) == len(rom_requirements) == len(screen_requirements) == n_models, "Array length mismatch"

    # 3. SETS
    model.I = pyo.RangeSet(1, n_models)  # 1-based indexing

    # 4. PARAMETERS
    model.profit = pyo.Param(model.I, initialize={i+1: profits[i] for i in range(n_models)})
    model.ram = pyo.Param(model.I, initialize={i+1: ram_requirements[i] for i in range(n_models)})
    model.rom = pyo.Param(model.I, initialize={i+1: rom_requirements[i] for i in range(n_models)})
    model.screen = pyo.Param(model.I, initialize={i+1: screen_requirements[i] for i in range(n_models)})

    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.profit[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)

    # 7. CONSTRAINTS
    def ram_constraint_rule(model):
        return sum(model.ram[i] * model.x[i] for i in model.I) <= total_ram
    model.ram_constraint = pyo.Constraint(rule=ram_constraint_rule)

    def rom_constraint_rule(model):
        return sum(model.rom[i] * model.x[i] for i in model.I) <= total_rom
    model.rom_constraint = pyo.Constraint(rule=rom_constraint_rule)

    def screen_constraint_rule(model):
        return sum(model.screen[i] * model.x[i] for i in model.I) <= total_screen
    model.screen_constraint = pyo.Constraint(rule=screen_constraint_rule)

    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')

    # Solve the model
    results = solver.solve(model, tee=True)

    # 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("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")

    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
phone_optimization()