from sqlalchemy import delete, select
from sqlalchemy.orm import Session

from app.models.product import Product
from app.models.scenario import CostingResult, Scenario
from app.services.costing_engine import calculate_product_cost


def run_scenario(db: Session, scenario: Scenario) -> list[dict]:
    db.execute(delete(CostingResult).where(CostingResult.scenario_id == scenario.id))
    products = db.scalars(select(Product).where(Product.tenant_id == scenario.tenant_id).order_by(Product.name)).all()
    results: list[dict] = []

    for product in products:
        breakdown = calculate_product_cost(db, product.id, overrides=scenario.overrides or {})
        db.add(
            CostingResult(
                tenant_id=scenario.tenant_id,
                scenario_id=scenario.id,
                product_id=product.id,
                finished_product_delivered=breakdown["finished_product_delivered"],
                distributor_price=breakdown["distributor_price"],
                wholesale_price=breakdown["wholesale_price"],
                warnings=breakdown["warnings"],
                details=breakdown,
            )
        )
        results.append(breakdown)

    scenario.status = "reviewed"
    db.commit()
    return results
