from __future__ import annotations

from decimal import Decimal
import json

from src.ctb_copy.runtime_paths import CopyResearchPaths
from src.ctb_copy.shadow.position_engine import ShadowPositionEngine, build_shadow_portfolio, compute_position_delta, summarize_shadow_run
from src.ctb_copy.shadow.position_journal import append_position_decisions, append_shadow_portfolio, write_shadow_result
from src.ctb_copy.shadow.shadow_models import ShadowLeaderPosition


def sample_position() -> ShadowLeaderPosition:
    return ShadowLeaderPosition(
        leader_id="leader-1",
        leader_type="wallet",
        symbol="ETH",
        side="long",
        size=Decimal("1"),
        leader_entry_price=Decimal("100"),
        current_mid=Decimal("100.1"),
        observed_at="2026-06-14T10:00:00+00:00",
        position_age_hours=Decimal("8"),
        leader_unrealized_pnl_pct=Decimal("0.1"),
        leader_liquidation_distance_pct=Decimal("20"),
        funding_rate=Decimal("0.001"),
        spread_pct=Decimal("0.03"),
        top_depth_usd=Decimal("50000"),
        source_snapshot_id="snap-1",
    )


def test_position_journal_writes_jsonl_outside_repo(tmp_path) -> None:
    paths = CopyResearchPaths(tmp_path / "copy_research")
    decision = ShadowPositionEngine().evaluate_delta(compute_position_delta(None, sample_position()))
    portfolio = build_shadow_portfolio([decision])
    summary = summarize_shadow_run("2026-06-14", [decision], paths)

    decision_path = append_position_decisions([decision], paths.shadow_position_decisions_file("2026-06-14"))
    portfolio_path = append_shadow_portfolio(portfolio, paths.shadow_portfolio_file("2026-06-14"))
    result_path = write_shadow_result(summary, paths.shadow_result_file("2026-06-14"))

    assert "Crypto_Agent" not in str(decision_path)
    assert json.loads(decision_path.read_text().splitlines()[0])["read_only_guard"]["read_only"] is True
    assert json.loads(portfolio_path.read_text().splitlines()[0])["total_notional_usd"] == "100"
    assert json.loads(result_path.read_text())["allowed_count"] == 1
