import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

import json
import pytest
from app import db
from app.jobs.grade_weekly_review import run_weekly_grading


@pytest.fixture(autouse=True)
def setup_db(tmp_path, monkeypatch):
    test_db = tmp_path / "test.db"
    monkeypatch.setattr(db, "DB_PATH", str(test_db))
    db.init_db()
    yield


def _seed_draw(drw_no=1153):
    db.upsert_draw({
        "drw_no": drw_no, "drw_date": "2026-05-09",
        "n1": 3, "n2": 11, "n3": 17, "n4": 25, "n5": 33, "n6": 41, "bonus": 8,
    })


def _seed_briefing(drw_no=1153):
    picks = {
        "core": [
            {"numbers": [3, 11, 17, 25, 33, 41], "risk_tag": "안정", "reason": "x"},  # 6
            {"numbers": [1, 2, 3, 4, 5, 6],      "risk_tag": "안정", "reason": "x"},  # 1
            {"numbers": [3, 11, 17, 4, 5, 6],    "risk_tag": "균형", "reason": "x"},  # 3
            {"numbers": [11, 25, 33, 7, 8, 9],   "risk_tag": "균형", "reason": "x"},  # 3
            {"numbers": [3, 11, 17, 25, 33, 9],  "risk_tag": "공격", "reason": "x"},  # 5
        ],
        "bonus": [], "extended": [], "pool": [],
    }
    db.save_briefing({
        "draw_no": drw_no, "picks": picks,
        "narrative": {"headline": "h", "summary_3lines": ["a", "b", "c"], "retrospective": ""},
        "confidence": 70, "model": "test",
    })


def test_grade_with_curator_only_no_purchase():
    _seed_draw()
    _seed_briefing()
    run_weekly_grading(1153)
    rev = db.get_review(1153)
    assert rev is not None
    assert rev["curator_avg_match"] == round((6+1+3+3+5)/5, 2)
    assert rev["curator_best_match"] == 6
    assert rev["curator_5plus_prizes"] == 4  # 6,3,3,5 ≥3 (네 개)
    assert rev["user_avg_match"] is None  # 구매 없음


def test_grade_with_no_briefing():
    _seed_draw()
    run_weekly_grading(1153)
    rev = db.get_review(1153)
    assert rev is not None
    assert rev["curator_avg_match"] is None
