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 ViewApiGoldenTest(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/view", params={"path": path})

        return asyncio.run(_run())

    def test_view_supported_text_success(self) -> None:
        file_path = self.root / "notes.md"
        file_path.write_text("# title\nhello\n", encoding="utf-8")

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

        self.assertEqual(response.status_code, 200)
        body = response.json()
        self.assertEqual(body["path"], "storage1/notes.md")
        self.assertEqual(body["name"], "notes.md")
        self.assertEqual(body["content_type"], "text/markdown")
        self.assertEqual(body["encoding"], "utf-8")
        self.assertFalse(body["truncated"])
        self.assertEqual(body["size"], len("# title\nhello\n".encode("utf-8")))
        self.assertEqual(body["content"], "# title\nhello\n")
        self.assertIn("modified", body)

    def test_view_unsupported_type(self) -> None:
        (self.root / "report.pdf").write_bytes(b"%PDF-1.4")

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

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

    def test_view_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_view_path_not_found(self) -> None:
        response = self._request("storage1/missing.txt")

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

    def test_view_traversal_attempt(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_view_truncated_response_for_large_file(self) -> None:
        content = "x" * (300 * 1024)
        (self.root / "big.log").write_text(content, encoding="utf-8")

        response = self._request("storage1/big.log")

        self.assertEqual(response.status_code, 200)
        body = response.json()
        self.assertTrue(body["truncated"])
        self.assertEqual(body["size"], len(content.encode("utf-8")))
        self.assertEqual(len(body["content"]), 256 * 1024)


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