# Complete DOCPLEX implementation

from docplex.mp.model import Model

def gas_company_optimization():
    """Optimize gas station allocations to maximize market value."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="gas_company")
    
    # Data: Market values for companies
    market_values = [12.5, 18.0, 14.0]
    n_companies = len(market_values)
    
    # Assumed data for constraints (these should be provided)
    sales = [40, 50, 30]  # Example sales data
    profits = [20, 25, 15]  # Example profit data
    assets = [80, 90, 70]  # Example asset data
    
    # Constraint bounds from the database
    total_sales_limit = 120.0
    minimum_profits_requirement = 60.0
    total_assets_limit = 250.0
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(sales) == len(profits) == len(assets) == n_companies, "Array length mismatch"
    safe_range = range(n_companies)  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for each company
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total market value of allocated companies
    objective = mdl.sum(market_values[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total Sales Limit Constraint
    total_sales = mdl.sum(sales[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_sales <= total_sales_limit, ctname="total_sales_limit")
    
    # Minimum Profits Requirement Constraint
    total_profits = mdl.sum(profits[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_profits >= minimum_profits_requirement, ctname="minimum_profits_requirement")
    
    # Total Assets Limit Constraint
    total_assets = mdl.sum(assets[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_assets <= total_assets_limit, ctname="total_assets_limit")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
gas_company_optimization()