"""Smoke-test the 4-tab FA service end-to-end against Postgres.

Each tab returns the same FATabResponse shape; KAM returns its own.
No writes — read-only. Run from project root with `py -3.12`.
"""
from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

from backend.models.database import SessionLocal
from backend.services.demand_service import DemandService


def show_tab(label: str, t: dict) -> None:
    h = t["headline"]
    print(f"--- {label} ---")
    print(f"  fa={h['fa']:.2f}  fa_signed={h['fa_signed']:.2f}  "
          f"bias={h['bias']:+.2f}  hit={h['hit_rate']:.2f}")
    print(f"  n_sku_weeks={h['n_sku_weeks']}  n_skus={h['n_skus']}  "
          f"n_weeks={h['n_weeks']}")
    if t.get("by_tier"):
        print(f"  by_tier: {[(b['label'], round(b['fa'], 1), b['n_sku_weeks']) for b in t['by_tier']]}")
    if t.get("by_xyz"):
        print(f"  by_xyz : {[(b['label'], round(b['fa'], 1), b['n_sku_weeks']) for b in t['by_xyz']]}")
    print(f"  weekly={len(t.get('weekly', []))}  "
          f"monthly={len(t.get('monthly', []))}  "
          f"top_impactors={len(t.get('top_impactors', []))}")
    if t.get("weekly"):
        w0 = t["weekly"][0]
        wN = t["weekly"][-1]
        print(f"  weekly[0]={w0['year_week']} fa={w0['fa']:.1f}  "
              f"weekly[-1]={wN['year_week']} fa={wN['fa']:.1f}")
    if t.get("monthly"):
        print(f"  monthly: {[(m['month'], round(m['fa'], 1)) for m in t['monthly']]}")
    if t.get("top_impactors"):
        ti = t["top_impactors"][0]
        print(f"  top1: {ti['sku']} abs_err={ti['abs_error']:.0f} "
              f"share={ti['share_of_total_error_pct']:.1f}% fa={ti['fa']:.1f}")
    if t.get("note"):
        print(f"  note: {t['note'][:120]}")
    print()


def main() -> int:
    with SessionLocal() as db:
        s = DemandService(db)
        show_tab("BACKTEST (all)",        s.get_fa_tab(mode="backtest"))
        show_tab("BACKTEST tier=GOLD",    s.get_fa_tab(mode="backtest", tier=["GOLD"]))
        show_tab("MODEL-ONLY",            s.get_fa_tab(mode="model_only"))
        show_tab("LIVE",                  s.get_fa_tab(mode="live"))

        # KAM has its own shape — print directly
        kam = s.get_kam_fa_summary()
        h = kam["headline"]
        print("--- KAM ---")
        print(f"  fa={h['fa']:.2f}  n_sku_weeks={h['n_sku_weeks']}  "
              f"by_person={len(kam['by_person'])}")
        if kam.get("note"):
            print(f"  note: {kam['note'][:120]}")
        print()

        # Legacy endpoint compat check
        legacy = s.get_fa_summary(tier="GOLD")
        print("--- LEGACY get_fa_summary(tier='GOLD') ---")
        print(f"  overall_fa={legacy['overall_fa']:.2f}  n={legacy['n']}  "
              f"hit={legacy['hit_rate']:.2f}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
