from __future__ import annotations

from pathlib import Path

from fastapi.testclient import TestClient

from beaver.interfaces.web.app import create_app
from beaver.services.agent_service import AgentService


def test_workspace_browser_api_manages_workspace_files(tmp_path: Path) -> None:
    service = AgentService(workspace=tmp_path)
    app = create_app(service=service, manage_service_lifecycle=False)

    with TestClient(app) as client:
        root = client.get("/api/workspace/browse")
        mkdir = client.post("/api/workspace/mkdir", params={"path": "docs"})
        upload = client.post(
            "/api/workspace/upload",
            data={"path": "docs"},
            files={"file": ("hello.txt", b"hello workspace", "text/plain")},
        )
        docs = client.get("/api/workspace/browse", params={"path": "docs"})
        download = client.get("/api/workspace/download", params={"path": "docs/hello.txt"})
        deleted = client.delete("/api/workspace/delete", params={"path": "docs/hello.txt"})
        after_delete = client.get("/api/workspace/browse", params={"path": "docs"})

    assert root.status_code == 200
    assert root.json()["path"] == ""
    assert all(item["name"] != "docs" for item in root.json()["items"])
    assert mkdir.status_code == 200
    assert mkdir.json()["path"] == "docs"
    assert upload.status_code == 200
    assert upload.json()["path"] == "docs/hello.txt"
    assert docs.status_code == 200
    assert [item["name"] for item in docs.json()["items"]] == ["hello.txt"]
    assert download.status_code == 200
    assert download.content == b"hello workspace"
    assert deleted.status_code == 200
    assert deleted.json() == {"ok": True}
    assert after_delete.status_code == 200
    assert after_delete.json()["items"] == []


def test_attachment_file_api_round_trips_uploaded_file(tmp_path: Path) -> None:
    service = AgentService(workspace=tmp_path)
    app = create_app(service=service, manage_service_lifecycle=False)

    with TestClient(app) as client:
        upload = client.post(
            "/api/files/upload",
            data={"session_id": "web:test"},
            files={"file": ("note.txt", b"hello attachment", "text/plain")},
        )
        file_id = upload.json()["file_id"]
        listed = client.get("/api/files", params={"session_id": "web:test"})
        download = client.get(f"/api/files/{file_id}")
        deleted = client.delete(f"/api/files/{file_id}")
        missing = client.get(f"/api/files/{file_id}")

    assert upload.status_code == 200
    assert upload.json()["name"] == "note.txt"
    assert upload.json()["url"] == f"/api/files/{file_id}"
    assert listed.status_code == 200
    assert [item["file_id"] for item in listed.json()] == [file_id]
    assert download.status_code == 200
    assert download.content == b"hello attachment"
    assert deleted.status_code == 200
    assert deleted.json() == {"ok": True}
    assert missing.status_code == 404
