import os
import gc
import json
import tempfile

import pytest
from fastapi.testclient import TestClient

from app import db as db_module


@pytest.fixture
def client(monkeypatch):
    fd, path = tempfile.mkstemp(suffix=".db")
    os.close(fd)
    monkeypatch.setattr(db_module, "DB_PATH", path)
    db_module.init_db()
    from app import main
    monkeypatch.setattr(main, "DB_PATH", path)
    with TestClient(main.app) as c:
        yield c
    gc.collect()
    for ext in ("", "-wal", "-shm"):
        try:
            os.remove(path + ext)
        except OSError:
            pass


def test_get_slate_writer_returns_default_when_unset(client):
    """DB에 없으면 코드 기본 마스터 프롬프트를 200으로 반환 (404 아님)."""
    resp = client.get("/api/insta/templates/prompts/slate_writer")
    assert resp.status_code == 200
    body = resp.json()
    assert body["is_default"] is True
    assert "{keyword}" in body["template"]
    assert "{category}" in body["template"]


def test_get_category_seeds_returns_default_when_unset(client):
    """category_seeds 기본값은 유효한 JSON (카테고리→시드 배열)."""
    resp = client.get("/api/insta/templates/prompts/category_seeds")
    assert resp.status_code == 200
    body = resp.json()
    assert body["is_default"] is True
    seeds = json.loads(body["template"])
    assert "economy" in seeds and isinstance(seeds["economy"], list)


def test_get_unknown_prompt_still_404(client):
    resp = client.get("/api/insta/templates/prompts/does_not_exist")
    assert resp.status_code == 404


def test_saved_template_overrides_default(client):
    """PUT로 저장하면 이후 GET은 저장본(is_default 없음)을 반환."""
    client.put("/api/insta/templates/prompts/slate_writer",
               json={"template": "내 커스텀 프롬프트", "description": "custom"})
    resp = client.get("/api/insta/templates/prompts/slate_writer")
    assert resp.status_code == 200
    body = resp.json()
    assert body["template"] == "내 커스텀 프롬프트"
    assert not body.get("is_default")
