"""HTTP surface for artifact sandbox inspection and download."""
from __future__ import annotations

import httpx
import pytest

from logos_adk.agent import Agent
from logos_adk.artifacts import ArtifactSandbox
from logos_adk.providers.mock import MockProvider
from logos_adk.serve_security import WORKSPACE_HEADER


async def _request(app, method: str, path: str, **kwargs):
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
        return await client.request(method, path, **kwargs)


@pytest.mark.asyncio
async def test_artifact_operator_surface_lists_and_downloads_workspace_artifacts(tmp_path, monkeypatch):
    from logos_adk.serve import create_app

    monkeypatch.setenv("LOGOS_ADK_ARTIFACTS_DIR", str(tmp_path / "artifacts"))
    sandbox = ArtifactSandbox()
    record = sandbox.create_text_artifact(
        workspace_id="acme",
        name="brief",
        content="launch copy",
        created_by="writer",
    )
    sandbox.create_text_artifact(
        workspace_id="other",
        name="hidden",
        content="other workspace",
        created_by="writer",
    )

    app = create_app([Agent("bot", model=MockProvider(responses=["ok"]))])
    headers = {WORKSPACE_HEADER: "acme"}

    listing = await _request(app, "GET", "/artifacts", headers=headers)
    detail = await _request(app, "GET", f"/artifacts/{record.id}", headers=headers)
    content = await _request(app, "GET", f"/artifacts/{record.id}/content", headers=headers)
    hidden = await _request(app, "GET", "/artifacts?workspace_id=other", headers=headers)

    assert listing.status_code == 200
    payload = listing.json()["items"]
    assert len(payload) == 1
    assert payload[0]["id"] == record.id
    assert payload[0]["download_path"] == f"/artifacts/{record.id}/content"

    assert detail.status_code == 200
    assert detail.json()["workspace_id"] == "acme"

    assert content.status_code == 200
    assert content.text == "launch copy"

    # Workspace scope from headers must win over arbitrary query access to another workspace.
    assert hidden.status_code == 200
    assert hidden.json()["items"] == payload
