"""模拟资金重置时同步清空交易记录。"""

from __future__ import annotations

from app.models.db import Database
from app.sim.ledger import Ledger


def test_reset_equity_clears_trade_history(tmp_path, monkeypatch) -> None:
    monkeypatch.setenv("MODE", "SIM")
    db = Database(tmp_path / "reset.db")
    with db._lock:
        db._conn.execute(
            """INSERT INTO groups(group_id, status, open_at_ms, close_at_ms, realized_pnl)
               VALUES ('G1','closed',1,2,-5.0)"""
        )
        db._conn.execute(
            """INSERT INTO fills(group_id, leg, action, side, inst_id, qty_eth,
               fill_px, fee, slip, notional, ts_ms)
               VALUES ('G1','perp','open','long','ETH-SWAP',1,2000,0.1,0,2000,1)"""
        )
        db._conn.execute(
            """INSERT INTO residual_options(
                 group_id, option_inst_id, option_side, option_qty_eth,
                 option_entry_px, status, created_at_ms
               ) VALUES ('G1','OPT','call',2,10,'pending',1)"""
        )
        db._conn.execute(
            """INSERT INTO ledger_entries(group_id, kind, amount, balance_after, note, ts_ms)
               VALUES ('G1','pnl',-5,9995,'t',2)"""
        )
        db._conn.execute(
            """UPDATE strategy_state SET rounds_done=3, window_key='w', rest_until_ms=99
               WHERE id=1"""
        )
        db._conn.commit()
    db.set_setting("risk_last_k", "1.5")

    Ledger(db).reset_equity(12000.0, note="test reset")

    assert db.fetchone("SELECT COUNT(*) AS c FROM groups")["c"] == 0
    assert db.fetchone("SELECT COUNT(*) AS c FROM fills")["c"] == 0
    assert db.fetchone("SELECT COUNT(*) AS c FROM residual_options")["c"] == 0
    entries = db.fetchall("SELECT kind, amount FROM ledger_entries")
    assert len(entries) == 1
    assert entries[0]["kind"] == "reset"
    assert float(entries[0]["amount"]) == 12000.0
    pos = db.fetchone("SELECT status, group_id FROM positions WHERE id=1")
    assert pos["status"] == "flat"
    assert pos["group_id"] is None
    st = db.fetchone(
        "SELECT rounds_done, window_key, rest_until_ms FROM strategy_state WHERE id=1"
    )
    assert int(st["rounds_done"]) == 0
    assert st["window_key"] is None
    assert st["rest_until_ms"] is None
    assert db.get_setting("risk_last_k") is None
    led = db.fetchone("SELECT equity, available, reserved FROM ledger_meta WHERE id=1")
    assert float(led["equity"]) == 12000.0
    assert float(led["available"]) == 12000.0
    assert float(led["reserved"]) == 0.0
    db.close()
