"""INIT_LINEAGE (2026-06-12): al primo avvio un worker eredita capital/real_capital
dal worker piu' recente di stessa strategia+asset su altro timeframe. Nato dallo
swap fade 1h->15m: i worker nuovi partivano dall'allocazione del pool scartando
il PnL del gemello (-16.8 di equity fantasma, riallineata a mano col seed)."""
import json
from types import SimpleNamespace

from src.live.strategy_worker import StrategyWorker


def _mk(tmp_path, tf, capital=100.0):
    w = StrategyWorker(strategy=SimpleNamespace(name="FAKE", fee_rt=0.001),
                       asset="BTC", tf=tf, capital=capital, position_size=0.5,
                       leverage=2.0, data_dir=tmp_path)
    w._notify = lambda *a, **k: None
    return w


def test_new_tf_inherits_capital_from_sibling(tmp_path):
    old = _mk(tmp_path, "1h", capital=100.0)
    old.capital = 181.19
    old.real_capital = 181.18
    old._save_state()

    new = _mk(tmp_path, "15m", capital=174.50)
    assert new.capital == 181.19
    assert new.real_capital == 181.18
    # la posizione NON si eredita
    assert new.in_position is False
    events = [json.loads(l)["event"] for l in new.trades_path.read_text().splitlines()]
    assert "INIT_LINEAGE" in events


def test_no_sibling_starts_from_allocation(tmp_path):
    w = _mk(tmp_path, "15m", capital=174.50)
    assert w.capital == 174.50
    events = [json.loads(l)["event"] for l in w.trades_path.read_text().splitlines()]
    assert "INIT_LINEAGE" not in events


def test_resume_ignores_lineage(tmp_path):
    old = _mk(tmp_path, "1h", capital=100.0)
    old.capital = 999.0
    old._save_state()
    new = _mk(tmp_path, "15m", capital=174.50)   # eredita 999
    new.capital = 150.0
    new._save_state()
    again = _mk(tmp_path, "15m", capital=174.50)  # RESUME, non lineage
    assert again.capital == 150.0
