from __future__ import annotations

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

import httpx
from starlette.requests import Request

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

from backend.app.api.routes_files import video as video_route
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 VideoApiGoldenTest(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)
        path_guard = PathGuard({"storage1": str(self.root)})
        self.service = FileOpsService(path_guard=path_guard, filesystem=FilesystemAdapter())

        async def _override_file_ops_service() -> FileOpsService:
            return self.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, headers: dict[str, str] | None = None) -> 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/video", params={"path": path}, headers=headers)

        return asyncio.run(_run())

    def _stream_route(self, path: str, headers: dict[str, str] | None = None) -> tuple[object, bytes]:
        async def _run() -> tuple[object, bytes]:
            scope = {
                "type": "http",
                "method": "GET",
                "path": "/api/files/video",
                "headers": [
                    (key.lower().encode("latin-1"), value.encode("latin-1"))
                    for key, value in (headers or {}).items()
                ],
            }
            response = await video_route(path=path, request=Request(scope), service=self.service)
            body = b""
            async for chunk in response.body_iterator:
                body += chunk
            return response, body

        return asyncio.run(_run())

    def test_video_stream_success_mp4(self) -> None:
        payload = b"\x00\x00\x00\x20ftypisom\x00\x00\x00\x00mp42"
        (self.root / "sample.mp4").write_bytes(payload)

        response, body = self._stream_route("storage1/sample.mp4")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.headers["content-type"], "video/mp4")
        self.assertEqual(response.headers["accept-ranges"], "bytes")
        self.assertEqual(response.headers["content-length"], str(len(payload)))
        self.assertEqual(body, payload)

    def test_video_stream_range_partial_content(self) -> None:
        payload = b"abcdefghijklmnopqrstuvwxyz"
        (self.root / "clip.mp4").write_bytes(payload)

        response, body = self._stream_route("storage1/clip.mp4", headers={"Range": "bytes=2-5"})

        self.assertEqual(response.status_code, 206)
        self.assertEqual(response.headers["accept-ranges"], "bytes")
        self.assertEqual(response.headers["content-range"], f"bytes 2-5/{len(payload)}")
        self.assertEqual(response.headers["content-length"], "4")
        self.assertEqual(body, b"cdef")

    def test_video_directory_type_conflict(self) -> None:
        (self.root / "media").mkdir()

        response = self._request("storage1/media")

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

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

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

    def test_video_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_video_non_video_type_blocked(self) -> None:
        (self.root / "notes.txt").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()
