import os, sys, tempfile, random as _r

# _shared lives in web-backend/_shared; add the parent dir so it can be found
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from fastapi.testclient import TestClient

def _client(monkeypatch):
    tmp = tempfile.mkdtemp()
    from app import db
    monkeypatch.setattr(db, "DB_PATH", os.path.join(tmp, "lotto.db"))
    db.init_db()
    from app.main import app
    return TestClient(app), db


def _seed_draws(db, n=40):
    rows = []
    _r.seed(2)
    for i in range(1, n + 1):
        s = sorted(_r.sample(range(1, 46), 6))
        rows.append({"drw_no": i, "drw_date": f"2020-01-{(i % 28) + 1:02d}",
                     "n1": s[0], "n2": s[1], "n3": s[2], "n4": s[3],
                     "n5": s[4], "n6": s[5], "bonus": ((s[5] % 45) + 1)})
    db.upsert_many_draws(rows)


def test_backtest_endpoints(monkeypatch):
    client, db = _client(monkeypatch)
    r = client.get("/api/lotto/backtest/track-record")
    assert r.status_code == 200
    assert "by_strategy" in r.json()
    r2 = client.get("/api/lotto/backtest/calibration?weeks=4")
    assert r2.status_code == 200
    assert isinstance(r2.json().get("history"), list)


def test_track_record_with_data(monkeypatch):
    """seed 40 draws + forward run → track-record contains random_null."""
    client, db_mod = _client(monkeypatch)
    _seed_draws(db_mod, 40)
    from app import backtest as bt
    bt.run_forward_purchase(40, k=20, pool_n=500, sample_seed=5)
    r = client.get("/api/lotto/backtest/track-record")
    assert r.status_code == 200
    body = r.json()
    assert "by_strategy" in body
    assert "random_null" in body["by_strategy"]


def test_review_known_and_unknown(monkeypatch):
    """Known draw with calibration → 200 + non-null winner_analysis; unknown → 404."""
    client, db_mod = _client(monkeypatch)
    _seed_draws(db_mod, 40)
    from app import backtest as bt
    bt.run_forward_purchase(40, k=20, pool_n=500, sample_seed=5)
    bt.calibrate_winner(40, sample_m=200)

    r = client.get("/api/lotto/backtest/review/40")
    assert r.status_code == 200
    body = r.json()
    assert body["winner_analysis"] is not None
    assert "score_total" in body["winner_analysis"]

    r2 = client.get("/api/lotto/backtest/review/99999")
    assert r2.status_code == 404


def test_calibration_weeks_bounds(monkeypatch):
    """weeks=0 and weeks=521 should be rejected with 422."""
    client, _ = _client(monkeypatch)
    r0 = client.get("/api/lotto/backtest/calibration?weeks=0")
    assert r0.status_code == 422
    r521 = client.get("/api/lotto/backtest/calibration?weeks=521")
    assert r521.status_code == 422
