import sys, os
sys.path.insert(0, os.path.dirname(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 test_save_briefing_4tier_roundtrip():
    payload = {
        "draw_no": 9999,
        "picks": {"core":[{"numbers":[1,2,3,4,5,6],"risk_tag":"안정","reason":"x"}],
                  "bonus":[], "extended":[], "pool":[]},
        "narrative": {"headline":"H","summary_3lines":["a","b","c"],"retrospective":"r"},
        "tier_rationale": {"bonus":"b1","extended":"e1","pool":"p1"},
        "confidence": 70,
        "model": "test",
    }
    bid = db.save_briefing(payload)
    assert bid > 0
    got = db.get_briefing(9999)
    assert got["picks"]["core"][0]["numbers"] == [1,2,3,4,5,6]
    assert got["tier_rationale"]["bonus"] == "b1"
    assert got["narrative"]["retrospective"] == "r"


def test_save_briefing_upsert_overwrites():
    db.save_briefing({
        "draw_no": 8888,
        "picks": {"core":[], "bonus":[], "extended":[], "pool":[]},
        "narrative": {"headline":"old","summary_3lines":["a","b","c"]},
        "confidence": 50, "model": "v1",
    })
    db.save_briefing({
        "draw_no": 8888,
        "picks": {"core":[{"numbers":[10,20,30,40,41,42],"risk_tag":"공격","reason":"y"}],
                  "bonus":[], "extended":[], "pool":[]},
        "narrative": {"headline":"new","summary_3lines":["x","y","z"]},
        "tier_rationale": {"bonus":"","extended":"","pool":""},
        "confidence": 90, "model": "v2",
    })
    got = db.get_briefing(8888)
    assert got["narrative"]["headline"] == "new"
    assert got["confidence"] == 90
    assert got["picks"]["core"][0]["risk_tag"] == "공격"
