from __future__ import annotations

import asyncio
import base64
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


PNG_1X1 = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
)


class FileInfoApiGoldenTest(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)
        self.service = FileOpsService(path_guard=PathGuard({"storage1": str(self.root)}), 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) -> 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/info", params={"path": path})

        return asyncio.run(_run())

    def test_file_info_success(self) -> None:
        file_path = self.root / "docs.txt"
        file_path.write_text("hello", encoding="utf-8")

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

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        self.assertEqual(payload["name"], "docs.txt")
        self.assertEqual(payload["path"], "storage1/docs.txt")
        self.assertEqual(payload["type"], "file")
        self.assertEqual(payload["size"], 5)
        self.assertEqual(payload["root"], "storage1")
        self.assertEqual(payload["extension"], ".txt")
        self.assertEqual(payload["content_type"], "text/plain")
        self.assertIn("modified", payload)
        self.assertIn("owner", payload)
        self.assertIn("group", payload)
        self.assertIsNone(payload["width"])
        self.assertIsNone(payload["height"])

    def test_directory_info_success(self) -> None:
        directory = self.root / "Media"
        directory.mkdir()

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

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        self.assertEqual(payload["name"], "Media")
        self.assertEqual(payload["path"], "storage1/Media")
        self.assertEqual(payload["type"], "directory")
        self.assertIsNone(payload["size"])
        self.assertEqual(payload["root"], "storage1")
        self.assertIsNone(payload["extension"])
        self.assertIsNone(payload["width"])
        self.assertIsNone(payload["height"])

    def test_image_info_has_width_and_height(self) -> None:
        file_path = self.root / "pixel.png"
        file_path.write_bytes(PNG_1X1)

        response = self._request("storage1/pixel.png")

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        self.assertEqual(payload["width"], 1)
        self.assertEqual(payload["height"], 1)
        self.assertEqual(payload["content_type"], "image/png")

    def test_info_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_info_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_info_invalid_root_alias(self) -> None:
        response = self._request("unknown/item.txt")

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

    def test_info_response_shape(self) -> None:
        file_path = self.root / "movie.mp4"
        file_path.write_bytes(b"012345")

        response = self._request("storage1/movie.mp4")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            set(response.json().keys()),
            {
                "name",
                "path",
                "type",
                "size",
                "modified",
                "root",
                "extension",
                "content_type",
                "owner",
                "group",
                "width",
                "height",
            },
        )


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