"""Export routes — the ONLY agent-token-reachable routes (explicit
allowlist; see services/agent_tokens.py for the AuthMiddleware wiring).

GET /api/export                 canonical full-DB export (harness shape)
GET /api/export/media-manifest  sha256 manifest of DATA_DIR media

Both accept EITHER a Pattern B grant (browser/user) OR
``Authorization: Bearer <AGENT_API_TOKEN>`` (CLI/agents — diff harness,
backups). The router-level dependency re-validates even though
AuthMiddleware already gated the request (defense in depth).
"""
from __future__ import annotations

from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session

from ..auth import get_authenticated_user
from ..config import get_settings
from ..db import get_db
from ..deps import current_garden_id, current_user
from ..services.agent_tokens import require_grant_or_agent_token
from ..services.export import build_media_manifest, export_garden

router = APIRouter(
    prefix="/api",
    tags=["export"],
    dependencies=[Depends(require_grant_or_agent_token)],
)

# Agent-token callers carry no user identity to resolve a membership from.
# Single-garden today (id=1, seeded by migrate_v1); when multi-garden lands,
# the token should become per-garden and this constant goes away.
AGENT_DEFAULT_GARDEN_ID = 1


def _export_garden_id(request: Request, db: Session = Depends(get_db)) -> int:
    """Garden scope for the export: membership-resolved for grant-authed
    users, the default garden for agent-token callers (no user identity)."""
    if get_authenticated_user(request) is not None:
        user = current_user(request, db)
        return current_garden_id(user, db)
    return AGENT_DEFAULT_GARDEN_ID


@router.get("/export")
def api_export(
    db: Session = Depends(get_db),
    garden_id: int = Depends(_export_garden_id),
) -> dict:
    """Canonical export of all 17 carried tables (harness-compatible shape:
    {"meta": ..., "tables": {...rows sorted by id...}})."""
    return export_garden(db, garden_id)


@router.get("/export/media-manifest")
def api_export_media_manifest() -> dict:
    """sha256 manifest of the media tree (notes/ + artifacts/) under
    DATA_DIR — same shape as scripts/media_manifest.py output."""
    return build_media_manifest(get_settings().data_dir)
