from __future__ import annotations

import asyncio
import sys
import tempfile
import time
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 FailingWriteFilesystemAdapter(FilesystemAdapter):
    def write_text_file(self, path: Path, content: str, encoding: str = "utf-8") -> dict:
        raise OSError("forced write failure")


class EditApiGoldenTest(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.path_guard = PathGuard({"storage1": str(self.root)})
        self._set_service(FilesystemAdapter())

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

    def _set_service(self, filesystem: FilesystemAdapter) -> None:
        service = FileOpsService(path_guard=self.path_guard, filesystem=filesystem)

        async def _override_file_ops_service() -> FileOpsService:
            return service

        app.dependency_overrides[get_file_ops_service] = _override_file_ops_service

    def _request(self, method: str, url: str, params: dict | None = None, payload: dict | 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:
                if method == "GET":
                    return await client.get(url, params=params)
                return await client.post(url, json=payload)

        return asyncio.run(_run())

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

        response = self._request("GET", "/api/files/view", params={"path": "storage1/notes.txt", "for_edit": "true"})

        self.assertEqual(response.status_code, 200)
        body = response.json()
        self.assertEqual(body["path"], "storage1/notes.txt")
        self.assertEqual(body["name"], "notes.txt")
        self.assertEqual(body["content"], "hello")
        self.assertFalse(body["truncated"])
        self.assertIn("modified", body)

    def test_edit_view_python_success(self) -> None:
        file_path = self.root / "script.py"
        file_path.write_text("print('hello')\n", encoding="utf-8")

        response = self._request("GET", "/api/files/view", params={"path": "storage1/script.py", "for_edit": "true"})

        self.assertEqual(response.status_code, 200)
        body = response.json()
        self.assertEqual(body["path"], "storage1/script.py")
        self.assertEqual(body["name"], "script.py")
        self.assertEqual(body["content_type"], "text/x-python")
        self.assertEqual(body["content"], "print('hello')\n")

    def test_edit_view_conf_success(self) -> None:
        file_path = self.root / "app.conf"
        file_path.write_text("enabled=true\n", encoding="utf-8")

        response = self._request("GET", "/api/files/view", params={"path": "storage1/app.conf", "for_edit": "true"})

        self.assertEqual(response.status_code, 200)
        body = response.json()
        self.assertEqual(body["path"], "storage1/app.conf")
        self.assertEqual(body["name"], "app.conf")
        self.assertEqual(body["content_type"], "text/plain")
        self.assertEqual(body["content"], "enabled=true\n")

    def test_save_success(self) -> None:
        file_path = self.root / "notes.txt"
        file_path.write_text("hello", encoding="utf-8")
        initial = self._request("GET", "/api/files/view", params={"path": "storage1/notes.txt", "for_edit": "true"}).json()

        response = self._request(
            "POST",
            "/api/files/save",
            payload={
                "path": "storage1/notes.txt",
                "content": "changed",
                "expected_modified": initial["modified"],
            },
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(file_path.read_text(encoding="utf-8"), "changed")
        self.assertEqual(response.json()["path"], "storage1/notes.txt")
        self.assertEqual(response.json()["size"], len("changed".encode("utf-8")))

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

        response = self._request("GET", "/api/files/view", params={"path": "storage1/report.pdf", "for_edit": "true"})

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

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

        response = self._request("GET", "/api/files/view", params={"path": "storage1/docs", "for_edit": "true"})

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

    def test_path_not_found(self) -> None:
        response = self._request("POST", "/api/files/save", payload={"path": "storage1/missing.txt", "content": "x", "expected_modified": "2026-01-01T00:00:00Z"})

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

    def test_traversal_attempt(self) -> None:
        response = self._request("POST", "/api/files/save", payload={"path": "storage1/../etc/passwd", "content": "x", "expected_modified": "2026-01-01T00:00:00Z"})

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

    def test_conflict_when_file_changed(self) -> None:
        file_path = self.root / "notes.txt"
        file_path.write_text("hello", encoding="utf-8")
        initial = self._request("GET", "/api/files/view", params={"path": "storage1/notes.txt", "for_edit": "true"}).json()
        time.sleep(0.02)
        file_path.write_text("changed elsewhere", encoding="utf-8")

        response = self._request(
            "POST",
            "/api/files/save",
            payload={
                "path": "storage1/notes.txt",
                "content": "local edit",
                "expected_modified": initial["modified"],
            },
        )

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

    def test_io_error_on_save_failure(self) -> None:
        file_path = self.root / "notes.txt"
        file_path.write_text("hello", encoding="utf-8")
        initial = self._request("GET", "/api/files/view", params={"path": "storage1/notes.txt", "for_edit": "true"}).json()
        self._set_service(FailingWriteFilesystemAdapter())

        response = self._request(
            "POST",
            "/api/files/save",
            payload={
                "path": "storage1/notes.txt",
                "content": "local edit",
                "expected_modified": initial["modified"],
            },
        )

        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.json()["error"]["code"], "io_error")

    def test_file_too_large_for_edit(self) -> None:
        content = "x" * (300 * 1024)
        (self.root / "big.txt").write_text(content, encoding="utf-8")

        response = self._request("GET", "/api/files/view", params={"path": "storage1/big.txt", "for_edit": "true"})

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


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