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

import pytest
from app import db


@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_briefing(drw=1153):
    picks = {
        "core":     [{"numbers": [1, 2, 3, 4, 5, 6],     "risk_tag": "안정", "reason": "x"}] * 5,
        "bonus":    [{"numbers": [7, 8, 9, 10, 11, 12],  "risk_tag": "균형", "reason": "x"}] * 5,
        "extended": [{"numbers": [13, 14, 15, 16, 17, 18], "risk_tag": "공격", "reason": "x"}] * 5,
        "pool":     [{"numbers": [19, 20, 21, 22, 23, 24], "risk_tag": "안정", "reason": "x"}] * 5,
    }
    db.save_briefing({
        "draw_no": drw, "picks": picks,
        "narrative": {"headline": "h", "summary_3lines": ["a", "b", "c"]},
        "confidence": 70, "model": "test",
    })


def test_bulk_core_inserts_5():
    _seed_briefing()
    r = db.bulk_insert_purchases_from_briefing(1153, "core", 5000)
    assert r["ok"] and r["sets"] == 5
    rows = db.get_purchases(draw_no=1153)
    assert len(rows) == 5
    assert all(row["source_strategy"] == "curator_core" for row in rows)


def test_bulk_full_inserts_20():
    _seed_briefing()
    r = db.bulk_insert_purchases_from_briefing(1153, "full", 20000)
    assert r["ok"] and r["sets"] == 20


def test_bulk_unknown_tier_mode():
    _seed_briefing()
    r = db.bulk_insert_purchases_from_briefing(1153, "garbage", 1000)
    assert r["ok"] is False and "garbage" in r["reason"]


def test_bulk_no_briefing():
    r = db.bulk_insert_purchases_from_briefing(9999, "core", 5000)
    assert r["ok"] is False and "not found" in r["reason"]
