"""Print Stock-Projection vs Scenario-Planner EUR walks side by side.

Goal: explain why the two charts show different numbers for the same
horizon. Computes both end-to-end against live DB.
"""
from backend.models.database import SessionLocal
from backend.services.supply_service import SupplyService
from backend.services.scenario_service import (
    compute_scenario, load_scenario_data, ScenarioParams,
)

db = SessionLocal()

# ---- Stock Projection (the chart in the user's screenshot) ----
proj = SupplyService(db).get_stock_projection_data()
proj_walk = {
    (w["year"], w["week"]): w["closing_value_eur"]
    for w in proj["weekly_aggregate"]
}
print(f"Stock Projection: {len(proj['rows'])} SKUs in universe")
print(f"  Total current value: €{proj['totals']['total_current_value_eur']:,.0f}")
print(f"  Forecasted (planned): €{proj['totals']['total_forecasted_value_eur']:,.0f}")
print(f"  Long-tail (unplanned): €{proj['totals']['total_longtail_value_eur']:,.0f}\n")

# ---- Scenario Planner (default: all suppliers, full window) ----
data = load_scenario_data(db)
params = ScenarioParams(
    suppliers=list(data.suppliers),
    window_start_cw=1,
    window_end_cw=53,
    stock_basis="wh_plus_stores",
    postpone_trigger=4.0,
    postpone_delay=4,
    cancel_on=True,
    cancel_threshold=16.0,
    target_eur=5_000_000.0,
    excluded_buyers=[],
    overrides={},
)
resp = compute_scenario(data, params)
scen_chart = {
    (p["year"], p["week"]): p["baseline_eur"]
    for p in resp["chart"]
}

print(f"Scenario Planner: {len(data.all_skus)} SKUs across {len(data.suppliers)} suppliers")
print(f"  current_eur (start): €{sum((data.wh_map.get(s,0) + data.stores_map.get(s,0)) * data.cost_map.get(s,0) for s in (set(data.wh_map) | set(data.stores_map))):,.0f}")

# ---- Side-by-side walk ----
print("\nCW         Stock Projection         Scenario Planner       Delta")
print("-" * 70)
keys = sorted(set(proj_walk) | set(scen_chart))[:14]
for (y, w) in keys:
    sp_v = proj_walk.get((y, w))
    sc_v = scen_chart.get((y, w))
    sp_s = f"€{sp_v:>12,.0f}" if sp_v is not None else "      —     "
    sc_s = f"€{sc_v:>12,.0f}" if sc_v is not None else "      —     "
    delta = (sc_v - sp_v) if (sp_v is not None and sc_v is not None) else None
    delta_s = f"€{delta:>+12,.0f}" if delta is not None else "      —     "
    print(f"{y}-W{w:02d}    {sp_s}        {sc_s}       {delta_s}")

# ---- Universe diff ----
proj_skus = {r["sku"] for r in proj["rows"]}
scen_skus = set(data.all_skus)
only_proj = proj_skus - scen_skus
only_scen = scen_skus - proj_skus
both = proj_skus & scen_skus
print(f"\nUniverse: projection={len(proj_skus)}  scenario={len(scen_skus)}  "
      f"intersection={len(both)}")
print(f"  Only in stock projection: {len(only_proj)}")
print(f"  Only in scenario planner: {len(only_scen)}")
if only_scen:
    sample = list(only_scen)[:5]
    print(f"  Sample scenario-only SKUs (first 5): {sample}")
    # How much value do they contribute on day 1?
    extra_start = sum(
        (data.wh_map.get(s, 0) + data.stores_map.get(s, 0)) * data.cost_map.get(s, 0)
        for s in only_scen
    )
    print(f"  Combined start value for those: €{extra_start:,.0f}")

db.close()
