from __future__ import annotations

import asyncio
import sys
import tempfile
import unittest
from pathlib import Path

import httpx

sys.path.insert(0, str(Path(__file__).resolve().parents[3]))

from backend.app.dependencies import get_file_ops_service
from backend.app.fs.filesystem_adapter import FilesystemAdapter
from backend.app.main import app
from backend.app.security.path_guard import PathGuard
from backend.app.services.file_ops_service import FileOpsService


class ThumbnailApiGoldenTest(unittest.TestCase):
    def setUp(self) -> None:
        self.temp_dir = tempfile.TemporaryDirectory()
        self.root = Path(self.temp_dir.name) / "root"
        self.root.mkdir(parents=True, exist_ok=True)
        service = FileOpsService(path_guard=PathGuard({"storage1": str(self.root)}), filesystem=FilesystemAdapter())

        async def _override_file_ops_service() -> FileOpsService:
            return service

        app.dependency_overrides[get_file_ops_service] = _override_file_ops_service

    def tearDown(self) -> None:
        app.dependency_overrides.clear()
        self.temp_dir.cleanup()

    def _request(self, path: str) -> httpx.Response:
        async def _run() -> httpx.Response:
            transport = httpx.ASGITransport(app=app)
            async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
                return await client.get("/api/files/thumbnail", params={"path": path})

        return asyncio.run(_run())

    def test_thumbnail_success_for_supported_image(self) -> None:
        image = self.root / "poster.jpg"
        image.write_bytes(b"\xff\xd8\xff\xe0thumbnail")

        response = self._request("storage1/poster.jpg")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.headers["content-type"], "image/jpeg")
        self.assertEqual(response.content, b"\xff\xd8\xff\xe0thumbnail")

    def test_thumbnail_not_found(self) -> None:
        response = self._request("storage1/missing.jpg")

        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.json()["error"]["code"], "path_not_found")

    def test_thumbnail_traversal_blocked(self) -> None:
        response = self._request("storage1/../etc/passwd")

        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.json()["error"]["code"], "path_traversal_detected")

    def test_thumbnail_invalid_root_alias(self) -> None:
        response = self._request("unknown/file.jpg")

        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.json()["error"]["code"], "invalid_root_alias")

    def test_thumbnail_non_image_blocked(self) -> None:
        text_file = self.root / "notes.txt"
        text_file.write_text("hello", encoding="utf-8")

        response = self._request("storage1/notes.txt")

        self.assertEqual(response.status_code, 409)
        self.assertEqual(response.json()["error"]["code"], "unsupported_type")


if __name__ == "__main__":
    unittest.main()
