import pytest
from fastapi.testclient import TestClient

from app.main import app
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


def _save_payload():
    return {
        "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",
    }


def test_health():
    with TestClient(app) as c:
        r = c.get("/health")
        assert r.status_code == 200
        assert r.json() == {"ok": True}


def test_save_list_get_cycle():
    with TestClient(app) as c:
        r = c.post("/api/tarot/readings", json=_save_payload())
        assert r.status_code == 200
        rid = r.json()["id"]
        r = c.get("/api/tarot/readings")
        assert r.json()["total"] == 1
        r = c.get(f"/api/tarot/readings/{rid}")
        assert r.json()["category"] == "연애"


def test_patch_favorite_and_note():
    with TestClient(app) as c:
        rid = c.post("/api/tarot/readings", json=_save_payload()).json()["id"]
        r = c.patch(f"/api/tarot/readings/{rid}", json={"favorite": True, "note": "n"})
        assert r.status_code == 200
        row = c.get(f"/api/tarot/readings/{rid}").json()
        assert row["favorite"] == 1
        assert row["note"] == "n"


def test_delete():
    with TestClient(app) as c:
        rid = c.post("/api/tarot/readings", json=_save_payload()).json()["id"]
        assert c.delete(f"/api/tarot/readings/{rid}").status_code == 200
        assert c.get(f"/api/tarot/readings/{rid}").status_code == 404


def test_get_404():
    with TestClient(app) as c:
        assert c.get("/api/tarot/readings/9999").status_code == 404
