"""Smoke reale: un giro di fetch v2 + build worker + un tick del portafoglio attivo.
NON apre ordini reali (paper). Verifica data layer v2 + sizing + ledger."""
import sys, shutil, tempfile
from pathlib import Path
from datetime import datetime, timezone, timedelta
import pandas as pd

PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))

from src.portfolio.base import load_active_portfolio
from src.portfolio.ledger import PortfolioLedger
from src.portfolio.runner import build_worker_for, _worker_equity
from src.live.cerbero_client import CerberoClient
from src.live.multi_runner import INSTRUMENT_MAP


def main():
    tmp = Path(tempfile.mkdtemp())
    p = load_active_portfolio(PROJECT_ROOT / "portfolios.yml")
    ledger = PortfolioLedger(p.code, total_capital=p.total_capital, data_dir=tmp)
    alloc = ledger.allocate({s.sid: 1.0 / len(p.sleeves) for s in p.sleeves})
    client = CerberoClient()
    print(f"Portafoglio attivo: {p.code} ({p.label}) — {len(p.sleeves)} sleeve, leva {p.leverage}x")
    end = datetime.now(timezone.utc); start = end - timedelta(days=60)
    ok = 0
    for s in p.sleeves[:3]:
        asset = s.asset or s.a
        inst = INSTRUMENT_MAP.get(asset, f"{asset}-PERPETUAL")
        candles = client.get_historical_v2(inst, start.strftime("%Y-%m-%d"),
                                           end.strftime("%Y-%m-%d"), s.tf)
        print(f"  {s.sid:<12s} {inst:<18s} candele={len(candles)}")
        ok += len(candles) > 0
    print(f"OK: {ok}/3 sleeve con feed v2 fresco. Ledger equity iniziale={ledger.equity}")
    shutil.rmtree(tmp, ignore_errors=True)


if __name__ == "__main__":
    main()
