# Complete PYOMO implementation

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

def company_office_optimization():
    """Optimize office space allocation to maximize market value"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    market_values = [12.0, 18.0, 14.5]  # Market values in billions
    sales = [6.5, 8.0, 7.0]  # Sales in billions
    stories = [12, 18, 15]  # Number of stories in each building
    minimum_sales_requirement = 20.0  # Minimum sales requirement in billions
    
    n_companies = len(market_values)
    n_buildings = len(stories)
    
    # CRITICAL: Validate array lengths before indexing
    assert len(market_values) == len(sales) == n_companies, "Array length mismatch for companies"
    assert len(stories) == n_buildings, "Array length mismatch for buildings"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_buildings)  # Buildings
    model.J = pyo.RangeSet(1, n_companies)  # Companies
    
    # 4. PARAMETERS
    model.market_value = pyo.Param(model.J, initialize={j+1: market_values[j] for j in range(n_companies)})
    model.sales = pyo.Param(model.J, initialize={j+1: sales[j] for j in range(n_companies)})
    model.stories = pyo.Param(model.I, initialize={i+1: stories[i] for i in range(n_buildings)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.market_value[j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Building Capacity Constraints
    def capacity_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= model.stories[i]
    model.capacity_constraint = pyo.Constraint(model.I, rule=capacity_rule)
    
    # Minimum Sales Performance Constraint
    def sales_rule(model):
        return sum(model.sales[j] * model.x[i, j] for i in model.I for j in model.J) >= minimum_sales_requirement
    model.sales_constraint = pyo.Constraint(rule=sales_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("\nAllocation decisions:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print allocations
                    print(f"Building {i} -> Company {j}")
        
    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
company_office_optimization()