import os, tempfile, importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient

def _client(monkeypatch, tmp):
    monkeypatch.setenv("IMAGE_DATA_DIR", tmp)
    monkeypatch.setenv("INTERNAL_API_KEY", "secret")
    import app.db as db; importlib.reload(db); db.init_db()
    import app.internal_router as ir; importlib.reload(ir)
    app = FastAPI(); app.include_router(ir.router)
    return TestClient(app), db

def test_update_requires_key(monkeypatch):
    with tempfile.TemporaryDirectory() as tmp:
        client, db = _client(monkeypatch, tmp)
        db.create_task("t1", "gpt_image", {"prompt": "x"})
        r = client.post("/api/internal/image/update",
                        json={"task_id": "t1", "status": "succeeded", "progress": 100})
        assert r.status_code == 422 or r.status_code == 401  # header 누락

def test_update_succeeds_with_key(monkeypatch):
    with tempfile.TemporaryDirectory() as tmp:
        client, db = _client(monkeypatch, tmp)
        db.create_task("t1", "gpt_image", {"prompt": "x"})
        r = client.post("/api/internal/image/update",
                        headers={"X-Internal-Key": "secret"},
                        json={"task_id": "t1", "status": "succeeded", "progress": 100,
                              "image_url": "/media/image/t1.png"})
        assert r.status_code == 200
        assert db.get_task("t1")["image_url"] == "/media/image/t1.png"

def test_update_unknown_task_404(monkeypatch):
    with tempfile.TemporaryDirectory() as tmp:
        client, db = _client(monkeypatch, tmp)
        r = client.post("/api/internal/image/update",
                        headers={"X-Internal-Key": "secret"},
                        json={"task_id": "nope", "status": "failed", "progress": 0})
        assert r.status_code == 404
