from pathlib import Path

import cv2
import numpy as np
from fastapi.testclient import TestClient

from app.blur_engine import Box
from app.main import app
import app.main as main_mod


class FakeDetector:
    def detect_bgr(self, frame):
        return [Box(20, 20, 60, 60, 1.0, "fake_sensitive")]


def make_sample(path: Path):
    img = np.zeros((100, 100, 3), dtype=np.uint8)
    img[20:60, 20:60] = 255
    cv2.imwrite(str(path), img)


def test_api_process_image_legacy(tmp_path, monkeypatch):
    monkeypatch.setattr(main_mod, "_detector", FakeDetector())
    src = tmp_path / "sample.png"
    make_sample(src)
    client = TestClient(app)
    with src.open("rb") as f:
        res = client.post("/api/process", files={"file": ("sample.png", f, "image/png")}, data={"blur_strength": "21", "margin": "0"})
    assert res.status_code == 200, res.text
    data = res.json()
    assert data["ok"] is True
    assert data["download_url"].startswith("/download/")


def test_upload_preview_render_image_flow(tmp_path, monkeypatch):
    monkeypatch.setattr(main_mod, "_detector", FakeDetector())
    src = tmp_path / "sample.png"
    make_sample(src)
    client = TestClient(app)
    with src.open("rb") as f:
        upload = client.post("/api/upload", files={"file": ("sample.png", f, "image/png")})
    assert upload.status_code == 200, upload.text
    file_id = upload.json()["file_id"]

    preview = client.post("/api/preview", data={"file_id": file_id, "blur_strength": "31", "margin": "0.1", "frame_index": "0"})
    assert preview.status_code == 200, preview.text
    assert preview.json()["preview_url"].endswith("_preview.png")
    assert preview.json()["meta"]["detections"] == 1

    render = client.post("/api/render", data={"file_id": file_id, "blur_strength": "31", "margin": "0.1", "detect_every": "5"})
    assert render.status_code == 200, render.text
    assert render.json()["download_url"].endswith("_blurred.png")
