import pytest
from app import db as db_module


@pytest.fixture(autouse=True)
def fresh_db(monkeypatch, tmp_path):
    db_file = tmp_path / "test_saju.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


# --- saju_records 5 tests ---

def test_saju_save_and_get():
    rid = db_module.save_saju_record({
        "birth_year": 1990, "birth_month": 5, "birth_day": 15, "birth_hour": 14,
        "gender": "male", "calendar_type": "solar",
        "saju_data": {"day_stem": "辛"},
        "analysis_data": {"element_balance": {"金": 3.0}},
        "daeun_data": [{"age": 10}],
        "interpretation_json": {"items": []},
        "model": "claude-sonnet-4-6",
        "tokens_in": 100, "tokens_out": 200, "cost_usd": 0.005,
    })
    assert rid > 0
    row = db_module.get_saju_record(rid)
    assert row["birth_year"] == 1990
    assert row["saju_data"]["day_stem"] == "辛"


def test_saju_list_with_favorite():
    for f in [0, 1, 0]:
        db_module.save_saju_record({
            "birth_year": 1990, "birth_month": 5, "birth_day": 15, "birth_hour": None,
            "gender": "male",
            "saju_data": {}, "analysis_data": {}, "daeun_data": [],
            "model": "x", "tokens_in": 0, "tokens_out": 0, "cost_usd": 0.0,
        })
    # set favorites
    rows = db_module.list_saju_records()["items"]
    db_module.update_saju_record(rows[0]["id"], favorite=True)
    res = db_module.list_saju_records(favorite=True)
    assert res["total"] == 1


def test_saju_update_favorite_and_memo():
    rid = db_module.save_saju_record({
        "birth_year": 1990, "birth_month": 5, "birth_day": 15, "birth_hour": None,
        "gender": "male",
        "saju_data": {}, "analysis_data": {}, "daeun_data": [],
        "model": "x",
    })
    db_module.update_saju_record(rid, favorite=True, memo="좋은 사주")
    row = db_module.get_saju_record(rid)
    assert row["favorite"] == 1
    assert row["memo"] == "좋은 사주"


def test_saju_delete():
    rid = db_module.save_saju_record({
        "birth_year": 1990, "birth_month": 5, "birth_day": 15, "birth_hour": None,
        "gender": "male",
        "saju_data": {}, "analysis_data": {}, "daeun_data": [],
        "model": "x",
    })
    db_module.delete_saju_record(rid)
    assert db_module.get_saju_record(rid) is None


def test_saju_get_nonexistent():
    assert db_module.get_saju_record(9999) is None


# --- compat_records 5 tests ---

def test_compat_save_and_get():
    rid = db_module.save_compat_record({
        "person_a": {"year": 1990},
        "person_b": {"year": 1992},
        "saju_a": {"day_stem": "辛"},
        "saju_b": {"day_stem": "丁"},
        "score": 85,
        "breakdown": {"day_master_element": {"score": 25}},
        "interpretation_json": {"summary": "좋음"},
        "model": "claude-sonnet-4-6",
        "tokens_in": 200, "tokens_out": 300, "cost_usd": 0.01,
    })
    assert rid > 0
    row = db_module.get_compat_record(rid)
    assert row["score"] == 85
    assert row["breakdown"]["day_master_element"]["score"] == 25


def test_compat_list_with_favorite():
    for _ in range(3):
        db_module.save_compat_record({
            "person_a": {}, "person_b": {},
            "saju_a": {}, "saju_b": {},
            "score": 50,
            "breakdown": {},
            "model": "x", "tokens_in": 0, "tokens_out": 0, "cost_usd": 0.0,
        })
    rows = db_module.list_compat_records()["items"]
    db_module.update_compat_record(rows[0]["id"], favorite=True)
    res = db_module.list_compat_records(favorite=True)
    assert res["total"] == 1


def test_compat_update_favorite_and_memo():
    rid = db_module.save_compat_record({
        "person_a": {}, "person_b": {},
        "saju_a": {}, "saju_b": {},
        "score": 70,
        "breakdown": {},
        "model": "x",
    })
    db_module.update_compat_record(rid, favorite=True, memo="궁합 좋음")
    row = db_module.get_compat_record(rid)
    assert row["favorite"] == 1
    assert row["memo"] == "궁합 좋음"


def test_compat_delete():
    rid = db_module.save_compat_record({
        "person_a": {}, "person_b": {},
        "saju_a": {}, "saju_b": {},
        "score": 50,
        "breakdown": {},
        "model": "x",
    })
    db_module.delete_compat_record(rid)
    assert db_module.get_compat_record(rid) is None


def test_compat_get_nonexistent():
    assert db_module.get_compat_record(9999) is None
