# Complete PYOMO implementation - Retry Attempt 1

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

def gas_station_allocation():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define the sets for stations and companies
    stations = [1, 2, 3]
    companies = [1, 2, 3]
    
    # Define the profit data
    profit_data = {
        (1, 1): 5000.0,
        (2, 2): 7500.0,
        (3, 3): 10000.0
    }
    
    # Define the maximum rank data
    max_rank_data = {
        1: 100,
        2: 150,
        3: 200
    }
    
    # 3. SETS
    model.S = pyo.Set(initialize=stations)
    model.C = pyo.Set(initialize=companies)
    
    # 4. PARAMETERS
    model.profit = pyo.Param(model.S, model.C, initialize=profit_data, default=0.0)
    model.max_rank = pyo.Param(model.C, initialize=max_rank_data)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.S, model.C, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.profit[s, c] * model.x[s, c] for s in model.S for c in model.C)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Single Assignment Constraint
    def single_assignment_rule(model, s):
        return sum(model.x[s, c] for c in model.C) <= 1
    model.single_assignment_constraint = pyo.Constraint(model.S, rule=single_assignment_rule)
    
    # Maximum Rank Constraint
    def max_rank_rule(model, c):
        return sum(model.x[s, c] for s in model.S) <= model.max_rank[c]
    model.max_rank_constraint = pyo.Constraint(model.C, rule=max_rank_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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nVariable values:")
        for s in model.S:
            for c in model.C:
                if pyo.value(model.x[s, c]) > 0.5:  # Only print assigned stations
                    print(f"Station {s} assigned to Company {c}")
        
    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 function
gas_station_allocation()