from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path

from src.tools.tradingview_community_track_record import evaluate_due_ideas, summarize_track_record


def _append(path: Path, row: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as fh:
        fh.write(json.dumps(row) + "\n")


def test_evaluate_due_ideas_scores_bullish_and_bearish_without_live_flags(tmp_path: Path) -> None:
    ideas = tmp_path / "research" / "tradingview_community_ideas.jsonl"
    _append(ideas, {
        "timestamp": "2026-06-27T00:00:00+00:00",
        "url": "https://www.tradingview.com/chart/BTCUSDT/a/",
        "author": "alice",
        "coin": "BTC",
        "bias": "bullish",
        "title": "BTC long",
        "price_at_capture_usd": "100",
        "research_only": True,
        "live_order_allowed": False,
    })
    _append(ideas, {
        "timestamp": "2026-06-27T00:00:00+00:00",
        "url": "https://www.tradingview.com/chart/ETHUSDT/b/",
        "author": "bob",
        "coin": "ETH",
        "bias": "bearish",
        "title": "ETH short",
        "price_at_capture_usd": "200",
        "research_only": True,
        "live_order_allowed": False,
    })

    result = evaluate_due_ideas(
        tmp_path,
        current_prices={"BTC": "110", "ETH": "180"},
        horizons_hours=(24,),
        now=datetime(2026, 6, 29, tzinfo=timezone.utc),
    )

    assert result["evaluated_new"] == 2
    summary = summarize_track_record(tmp_path)
    assert summary["evaluated"] == 2
    assert summary["by_author"]["alice"]["hitrate_pct"] == "100.00"
    assert summary["by_author"]["bob"]["hitrate_pct"] == "100.00"

    rows = [json.loads(line) for line in (tmp_path / "research" / "tradingview_community_idea_evaluations.jsonl").read_text().splitlines()]
    assert all(row["research_only"] is True for row in rows)
    assert all(row["live_order_allowed"] is False for row in rows)
    assert all(row["mainnet_signed_action"] is False for row in rows)


def test_evaluate_due_ideas_waits_until_horizon_and_dedupes(tmp_path: Path) -> None:
    ideas = tmp_path / "research" / "tradingview_community_ideas.jsonl"
    _append(ideas, {
        "timestamp": "2026-06-29T00:00:00+00:00",
        "url": "https://www.tradingview.com/chart/BTCUSDT/a/",
        "author": "alice",
        "coin": "BTC",
        "bias": "bullish",
        "title": "BTC long",
        "price_at_capture_usd": "100",
    })

    early = evaluate_due_ideas(tmp_path, current_prices={"BTC": "110"}, horizons_hours=(24,), now=datetime(2026, 6, 29, 12, tzinfo=timezone.utc))
    assert early["evaluated_new"] == 0

    due = evaluate_due_ideas(tmp_path, current_prices={"BTC": "110"}, horizons_hours=(24,), now=datetime(2026, 6, 30, 1, tzinfo=timezone.utc))
    again = evaluate_due_ideas(tmp_path, current_prices={"BTC": "120"}, horizons_hours=(24,), now=datetime(2026, 6, 30, 2, tzinfo=timezone.utc))
    assert due["evaluated_new"] == 1
    assert again["evaluated_new"] == 0
