# Complete PYOMO implementation

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

def mountain_photos_optimization():
    """Optimization model for selecting camera lenses for photographing mountains."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Lenses data
    lenses_data = {
        1: {'cost': 500.0, 'focal_length_mm': 24, 'max_aperture': 1.8},
        2: {'cost': 750.0, 'focal_length_mm': 50, 'max_aperture': 2.8},
        3: {'cost': 1000.0, 'focal_length_mm': 85, 'max_aperture': 4.0}
    }
    
    # Mountains data
    mountains_data = {
        1: {'minimum_focal_length': 24, 'minimum_aperture': 1.8},
        2: {'minimum_focal_length': 50, 'minimum_aperture': 2.8},
        3: {'minimum_focal_length': 85, 'minimum_aperture': 4.0}
    }
    
    # Validate data lengths
    assert len(lenses_data) > 0, "Lenses data is empty"
    assert len(mountains_data) > 0, "Mountains data is empty"
    
    # 3. SETS
    model.L = pyo.Set(initialize=lenses_data.keys())  # Set of lenses
    model.M = pyo.Set(initialize=mountains_data.keys())  # Set of mountains
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.L, initialize={l: lenses_data[l]['cost'] for l in model.L})
    model.focal_length = pyo.Param(model.L, initialize={l: lenses_data[l]['focal_length_mm'] for l in model.L})
    model.max_aperture = pyo.Param(model.L, initialize={l: lenses_data[l]['max_aperture'] for l in model.L})
    
    model.min_focal_length = pyo.Param(model.M, initialize={m: mountains_data[m]['minimum_focal_length'] for m in model.M})
    model.min_aperture = pyo.Param(model.M, initialize={m: mountains_data[m]['minimum_aperture'] for m in model.M})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.L, model.M, within=pyo.Binary)  # Binary decision variable
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[l] * model.x[l, m] for l in model.L for m in model.M)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Minimum Lenses per Mountain
    def min_lenses_rule(model, m):
        return sum(model.x[l, m] for l in model.L) >= 1
    model.min_lenses_constraint = pyo.Constraint(model.M, rule=min_lenses_rule)
    
    # Maximum Lenses per Mountain
    def max_lenses_rule(model, m):
        return sum(model.x[l, m] for l in model.L) <= 3
    model.max_lenses_constraint = pyo.Constraint(model.M, rule=max_lenses_rule)
    
    # Focal Length Requirement
    def focal_length_rule(model, l, m):
        return model.focal_length[l] * model.x[l, m] >= model.min_focal_length[m] * model.x[l, m]
    model.focal_length_constraint = pyo.Constraint(model.L, model.M, rule=focal_length_rule)
    
    # Aperture Requirement
    def aperture_rule(model, l, m):
        return model.max_aperture[l] * model.x[l, m] >= model.min_aperture[m] * model.x[l, m]
    model.aperture_constraint = pyo.Constraint(model.L, model.M, rule=aperture_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
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected lenses for each mountain:")
        for m in model.M:
            print(f"Mountain {m}:")
            for l in model.L:
                if pyo.value(model.x[l, m]) > 0.5:  # Only print selected lenses
                    print(f"  Lens {l} selected")
        
    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

# Execute the optimization
if __name__ == "__main__":
    mountain_photos_optimization()