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 PdfApiGoldenTest(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)})
        service = FileOpsService(path_guard=path_guard, 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/pdf", params={"path": path})

        return asyncio.run(_run())

    def test_pdf_endpoint_success(self) -> None:
        payload = b"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n"
        (self.root / "sample.pdf").write_bytes(payload)

        response = self._request("storage1/sample.pdf")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.headers["content-type"], "application/pdf")
        self.assertEqual(response.headers["content-length"], str(len(payload)))
        self.assertEqual(response.content, payload)

    def test_pdf_directory_type_conflict(self) -> None:
        (self.root / "docs").mkdir()

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

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

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

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

    def test_pdf_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_pdf_invalid_root_alias(self) -> None:
        response = self._request("unknown/sample.pdf")

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

    def test_pdf_non_pdf_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()
