import os
import pytest
from app import db, config


@pytest.fixture
def fresh_db(tmp_path, monkeypatch):
    monkeypatch.setattr(config, "DB_PATH", str(tmp_path / "insta.db"))
    monkeypatch.setattr(db, "DB_PATH", str(tmp_path / "insta.db"))
    db.init_db()


def test_set_slate_decision_approved_publishes(fresh_db):
    sid = db.add_card_slate({"keyword": "금리", "category": "economy"})
    db.set_slate_decision(sid, "approved")
    s = db.get_card_slate(sid)
    assert s["status"] == "published"
    assert s["published_at"] is not None
    assert s["decision_at"] is not None


def test_set_slate_decision_rejected(fresh_db):
    sid = db.add_card_slate({"keyword": "환율", "category": "economy"})
    db.set_slate_decision(sid, "rejected")
    s = db.get_card_slate(sid)
    assert s["status"] == "rejected"
    assert s["decision_at"] is not None
    assert s["published_at"] is None


def test_set_slate_decision_idempotent(fresh_db):
    sid = db.add_card_slate({"keyword": "주식", "category": "economy"})
    db.set_slate_decision(sid, "approved")
    first = db.get_card_slate(sid)["published_at"]
    db.set_slate_decision(sid, "approved")
    assert db.get_card_slate(sid)["published_at"] == first


def test_list_recent_issued_topics(fresh_db):
    a = db.add_card_slate({"keyword": "금리", "category": "economy"})
    b = db.add_card_slate({"keyword": "우울증", "category": "psychology"})
    db.set_slate_decision(a, "approved")
    db.set_slate_decision(b, "rejected")
    topics = db.list_recent_issued_topics(window_days=14)
    pairs = {(t["keyword"], t["category"]) for t in topics}
    assert ("금리", "economy") in pairs
    assert ("우울증", "psychology") in pairs
