"""Artifact routes - /artifacts/* endpoints."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import PlainTextResponse

from logos_adk.artifacts import ArtifactSandbox
from logos_adk.serve_security import WORKSPACE_HEADER

router = APIRouter(tags=["artifacts"])


def _get_sandbox() -> ArtifactSandbox:
    """Get the global artifact sandbox instance."""
    return ArtifactSandbox()


@router.get("/artifacts")
async def list_artifacts(
    workspace_id: str | None = Query(None),
    request: Request = None,  # type: ignore[assignment]
) -> dict[str, Any]:
    """List artifacts - workspace header takes precedence over query param."""
    sandbox = _get_sandbox()

    workspace = None
    if request is not None:
        workspace = request.headers.get(WORKSPACE_HEADER)

    effective_workspace = workspace if workspace else workspace_id

    records = sandbox.list_artifacts(workspace_id=effective_workspace)

    return {
        "items": [
            {
                "id": r.id,
                "name": r.name,
                "workspace_id": r.workspace_id,
                "kind": r.kind,
                "download_path": f"/artifacts/{r.id}/content",
            }
            for r in records
        ],
    }


@router.get("/artifacts/{artifact_id}")
async def get_artifact(
    artifact_id: str,
    request: Request = None,  # type: ignore[assignment]
) -> dict[str, Any]:
    """Get artifact metadata."""
    sandbox = _get_sandbox()

    workspace = None
    if request is not None:
        workspace = request.headers.get(WORKSPACE_HEADER)

    record = sandbox.get_artifact(artifact_id)
    if record is None:
        raise HTTPException(status_code=404, detail="Artifact not found")

    if workspace and record.workspace_id != workspace:
        raise HTTPException(status_code=404, detail="Artifact not found")

    return {
        "id": record.id,
        "name": record.name,
        "workspace_id": record.workspace_id,
        "kind": record.kind,
        "download_path": f"/artifacts/{record.id}/content",
    }


@router.get("/artifacts/{artifact_id}/content", response_class=PlainTextResponse)
async def get_artifact_content(
    artifact_id: str,
    request: Request = None,  # type: ignore[assignment]
) -> str:
    """Download artifact content."""
    sandbox = _get_sandbox()

    workspace = None
    if request is not None:
        workspace = request.headers.get(WORKSPACE_HEADER)

    record = sandbox.get_artifact(artifact_id)
    if record is None:
        raise HTTPException(status_code=404, detail="Artifact not found")

    if workspace and record.workspace_id != workspace:
        raise HTTPException(status_code=404, detail="Artifact not found")

    try:
        content = sandbox.read_text(artifact_id)
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail="Artifact not found")

    return content


__all__ = ["router"]
