from pathlib import Path
from src.portfolio.ledger import PortfolioLedger


def test_alloc_split_by_weights(tmp_path):
    L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
    alloc = L.allocate({"a": 0.6, "b": 0.4})
    assert alloc == {"a": 600.0, "b": 400.0}


def test_alloc_conserves_total_with_reserved(tmp_path):
    # un worker in posizione (reserved) trattiene capitale != alloc: i flat si
    # dividono il RESTO per peso rinormalizzato e Σalloc == total (no doppio conteggio).
    # Regressione del bug 2026-06-13 (MR02_BTC 15m in-pos al ribilancio: +4.77 fantasma).
    L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
    alloc = L.allocate({"a": 0.5, "b": 0.25, "c": 0.25}, reserved={"a": 181.0})
    assert abs(sum(alloc.values()) - 1000.0) < 1e-6     # equity conservata
    assert alloc["a"] == 181.0                           # in-pos tiene il suo
    # b e c si dividono 819 per peso 0.25/0.25 -> 409.5 ciascuno
    assert abs(alloc["b"] - 409.5) < 1e-6 and abs(alloc["c"] - 409.5) < 1e-6


def test_alloc_no_reserved_is_legacy(tmp_path):
    L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
    assert L.allocate({"a": 0.6, "b": 0.4}) == {"a": 600.0, "b": 400.0}


def test_update_tracks_equity_and_dd(tmp_path):
    L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
    L.update_equity({"a": 700.0, "b": 500.0})
    assert L.equity == 1200.0 and L.peak == 1200.0 and L.max_dd == 0.0
    L.update_equity({"a": 500.0, "b": 400.0})
    assert L.equity == 900.0
    assert abs(L.max_dd - 25.0) < 1e-9


def test_persist_and_resume(tmp_path):
    L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
    L.update_equity({"a": 1100.0})
    L.save()
    L2 = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
    assert L2.equity == 1100.0 and L2.peak == 1100.0
    assert (tmp_path / "PORTX" / "equity.jsonl").exists()
