import os
import pytest

from app import db as db_module


@pytest.fixture(autouse=True)
def fresh_db(monkeypatch, tmp_path):
    db_file = tmp_path / "test_tarot.db"
    monkeypatch.setattr(db_module, "DB_PATH", str(db_file))
    db_module.init_db()
    yield
    try:
        if db_file.exists():
            db_file.unlink()
    except PermissionError:
        pass  # Windows SQLite WAL 잠금


def test_save_and_get():
    rid = db_module.save_tarot_reading({
        "spread_type": "three_card",
        "category": "연애",
        "question": "Q",
        "cards": [{"position": "과거", "card_id": "the-fool", "reversed": False}],
        "interpretation_json": {"summary": "S", "cards": [], "interactions": [], "advice": "A", "warning": None, "confidence": "medium"},
        "model": "claude-sonnet-4-6",
        "tokens_in": 100, "tokens_out": 200, "cost_usd": 0.005,
        "confidence": "medium",
    })
    assert rid > 0
    row = db_module.get_tarot_reading(rid)
    assert row["id"] == rid
    assert row["category"] == "연애"
    assert row["interpretation_json"]["summary"] == "S"
    assert row["favorite"] == 0


def test_list_with_filters():
    for cat in ["연애", "연애", "재물"]:
        db_module.save_tarot_reading({
            "spread_type": "three_card", "category": cat, "question": "Q",
            "cards": [], "interpretation_json": {"summary": "S", "cards": [], "interactions": [], "advice": "", "warning": None, "confidence": "low"},
            "model": "x", "tokens_in": 0, "tokens_out": 0, "cost_usd": 0.0, "confidence": "low",
        })
    res = db_module.list_tarot_readings(page=1, size=10, category="연애")
    assert res["total"] == 2
    assert all(r["category"] == "연애" for r in res["items"])


def test_update_favorite_and_note():
    rid = db_module.save_tarot_reading({
        "spread_type": "one_card", "category": None, "question": None,
        "cards": [], "interpretation_json": None,
        "model": "x", "tokens_in": 0, "tokens_out": 0, "cost_usd": 0.0, "confidence": None,
    })
    db_module.update_tarot_reading(rid, favorite=True, note="좋아요")
    row = db_module.get_tarot_reading(rid)
    assert row["favorite"] == 1
    assert row["note"] == "좋아요"


def test_delete():
    rid = db_module.save_tarot_reading({
        "spread_type": "one_card", "category": None, "question": None,
        "cards": [], "interpretation_json": None,
        "model": "x", "tokens_in": 0, "tokens_out": 0, "cost_usd": 0.0, "confidence": None,
    })
    db_module.delete_tarot_reading(rid)
    assert db_module.get_tarot_reading(rid) is None
