import json
from datetime import datetime, timezone


def _write_jsonl(path, events):
    path.write_text("\n".join(json.dumps(e) for e in events) + "\n", encoding="utf-8")


def test_match_entries_to_previous_market_context(tmp_path):
    from signal_correlation import correlate_trades_with_context

    journal = tmp_path / "trade_journal.jsonl"
    context = tmp_path / "market_context.jsonl"
    _write_jsonl(context, [
        {"event_type": "market_context", "ts": "2026-01-01T10:00:00+00:00", "coin": "BTC", "tags": ["trend_down"], "reliability_score": 0.7, "indicators": {"rsi_14": 45}},
        {"event_type": "market_context", "ts": "2026-01-01T10:10:00+00:00", "coin": "BTC", "tags": ["trend_up", "oi_available"], "reliability_score": 0.9, "indicators": {"rsi_14": 62}},
        {"event_type": "market_context", "ts": "2026-01-01T10:20:00+00:00", "coin": "ETH", "tags": ["rsi_oversold"], "reliability_score": 0.8, "indicators": {"rsi_14": 29}},
    ])
    _write_jsonl(journal, [
        {"event_type": "entry", "ts": "2026-01-01T10:12:00+00:00", "coin": "BTC", "price": 100, "size": 1, "dry_run": False, "reason": "flash_crash"},
        {"event_type": "exit", "ts": "2026-01-01T10:40:00+00:00", "coin": "BTC", "price": 110, "size": 1, "dry_run": False, "reason": "TRAIL", "realized_pnl_usd": 10},
    ])

    result = correlate_trades_with_context(journal, context)

    assert len(result.matches) == 1
    match = result.matches[0]
    assert match.coin == "BTC"
    assert match.context_tags == ("trend_up", "oi_available")
    assert match.realized_pnl_usd == 10
    assert match.exit_reason == "TRAIL"
    assert match.time_in_trade_minutes == 28


def test_tag_stats_aggregate_winrate_and_returns(tmp_path):
    from signal_correlation import correlate_trades_with_context

    journal = tmp_path / "trade_journal.jsonl"
    context = tmp_path / "market_context.jsonl"
    _write_jsonl(context, [
        {"event_type": "market_context", "ts": "2026-01-01T10:00:00+00:00", "coin": "BTC", "tags": ["trend_up"], "reliability_score": 0.9, "indicators": {}},
        {"event_type": "market_context", "ts": "2026-01-01T11:00:00+00:00", "coin": "ETH", "tags": ["trend_up", "rsi_oversold"], "reliability_score": 0.8, "indicators": {}},
    ])
    _write_jsonl(journal, [
        {"event_type": "entry", "ts": "2026-01-01T10:05:00+00:00", "coin": "BTC", "price": 100, "size": 1, "dry_run": False},
        {"event_type": "exit", "ts": "2026-01-01T10:10:00+00:00", "coin": "BTC", "price": 101, "size": 1, "dry_run": False, "realized_pnl_usd": 1, "reason": "BE"},
        {"event_type": "entry", "ts": "2026-01-01T11:05:00+00:00", "coin": "ETH", "price": 100, "size": 1, "dry_run": False},
        {"event_type": "exit", "ts": "2026-01-01T11:20:00+00:00", "coin": "ETH", "price": 98, "size": 1, "dry_run": False, "realized_pnl_usd": -2, "reason": "SL"},
    ])

    result = correlate_trades_with_context(journal, context)

    assert result.tag_stats["trend_up"].sample_size == 2
    assert result.tag_stats["trend_up"].win_rate == 0.5
    assert result.tag_stats["trend_up"].avg_pnl_usd == -0.5
    assert result.tag_stats["rsi_oversold"].sample_size == 1
    assert result.tag_stats["rsi_oversold"].win_rate == 0.0


def test_report_is_observational_until_minimum_sample_size(tmp_path):
    from signal_correlation import correlate_trades_with_context, render_correlation_report

    journal = tmp_path / "trade_journal.jsonl"
    context = tmp_path / "market_context.jsonl"
    _write_jsonl(context, [{"event_type": "market_context", "ts": "2026-01-01T10:00:00+00:00", "coin": "BTC", "tags": ["trend_up"], "reliability_score": 0.9, "indicators": {}}])
    _write_jsonl(journal, [
        {"event_type": "entry", "ts": "2026-01-01T10:05:00+00:00", "coin": "BTC", "price": 100, "size": 1, "dry_run": False},
        {"event_type": "exit", "ts": "2026-01-01T10:20:00+00:00", "coin": "BTC", "price": 102, "size": 1, "dry_run": False, "realized_pnl_usd": 2, "reason": "TRAIL"},
    ])

    result = correlate_trades_with_context(journal, context)
    report = render_correlation_report(result, min_samples=5)

    assert "Observation only" in report
    assert "keine Strategieänderung" in report
    assert "trend_up" in report


def test_open_entries_are_excluded_from_closed_trade_stats(tmp_path):
    from signal_correlation import correlate_trades_with_context

    journal = tmp_path / "trade_journal.jsonl"
    context = tmp_path / "market_context.jsonl"
    _write_jsonl(context, [{"event_type": "market_context", "ts": "2026-01-01T10:00:00+00:00", "coin": "BTC", "tags": ["trend_up"], "reliability_score": 0.9, "indicators": {}}])
    _write_jsonl(journal, [{"event_type": "entry", "ts": "2026-01-01T10:05:00+00:00", "coin": "BTC", "price": 100, "size": 1, "dry_run": False}])

    result = correlate_trades_with_context(journal, context)

    assert result.closed_trade_count == 0
    assert result.open_entry_count == 1
    assert result.matches == []
