# Complete PYOMO implementation

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

def gas_company_optimization():
    """Optimization model for gas company allocation problem"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Assume sales, profits, and assets data for each company
    sales = [50, 40, 30]  # Example sales data
    profits = [20, 25, 15]  # Example profits data
    assets = [100, 80, 70]  # Example assets data
    
    # Market values from the database
    market_values = [12.5, 18.0, 14.0]
    
    # Constraint bounds from the database
    total_sales_limit = 120.0
    minimum_profits_requirement = 60.0
    total_assets_limit = 250.0
    
    # CRITICAL: Validate array lengths before indexing
    n_companies = len(market_values)
    assert len(sales) == len(profits) == len(assets) == n_companies, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_companies)  # 1-based indexing
    
    # 4. PARAMETERS
    model.market_value = pyo.Param(model.I, initialize={i+1: market_values[i] for i in range(n_companies)})
    model.sales = pyo.Param(model.I, initialize={i+1: sales[i] for i in range(n_companies)})
    model.profits = pyo.Param(model.I, initialize={i+1: profits[i] for i in range(n_companies)})
    model.assets = pyo.Param(model.I, initialize={i+1: assets[i] for i in range(n_companies)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.market_value[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def sales_constraint_rule(model):
        return sum(model.sales[i] * model.x[i] for i in model.I) <= total_sales_limit
    model.sales_constraint = pyo.Constraint(rule=sales_constraint_rule)
    
    def profits_constraint_rule(model):
        return sum(model.profits[i] * model.x[i] for i in model.I) >= minimum_profits_requirement
    model.profits_constraint = pyo.Constraint(rule=profits_constraint_rule)
    
    def assets_constraint_rule(model):
        return sum(model.assets[i] * model.x[i] for i in model.I) <= total_assets_limit
    model.assets_constraint = pyo.Constraint(rule=assets_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
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective):.3f}")
        
        # 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}] = {int(x_val)}")
        
    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
gas_company_optimization()