"""Publish/release log (Pillar 6): POST /releases captures a point-in-time
snapshot of what's currently published/active across Workflows, Forms,
Pages, Dashboards, and Menus and stores it under a name/description. This
is an audit trail, not a rollback mechanism — see app/crud/release.py.
Gated under the "settings" module (mirrors audit.py/vendors.py, which also
have no dedicated RBAC module of their own) — creating a release is treated
as a "publish" action, viewing the log as "view"."""

import uuid

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.permissions import require_permission
from app.core.security import AuthContext, get_auth_context
from app.crud.base import CRUDBase
from app.crud.release import capture_snapshot, snapshot_counts
from app.models.release import Release
from app.schemas.release import ReleaseCreate, ReleaseRead, ReleaseSummary

router = APIRouter(prefix="/releases", tags=["releases"])
crud = CRUDBase[Release, ReleaseCreate, ReleaseCreate](Release)


@router.get("", response_model=list[ReleaseSummary])
async def list_releases(
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "view")),
) -> list[ReleaseSummary]:
    releases = await crud.list(db, ctx.tenant_id, limit=200)
    return [
        ReleaseSummary(
            id=r.id,
            tenant_id=r.tenant_id,
            name=r.name,
            description=r.description,
            created_by=r.created_by,
            created_at=r.created_at,
            counts=snapshot_counts(r.snapshot),
        )
        for r in sorted(releases, key=lambda r: r.created_at, reverse=True)
    ]


@router.get("/{release_id}", response_model=ReleaseRead)
async def get_release(
    release_id: uuid.UUID,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "view")),
) -> Release:
    return await crud.get(db, ctx.tenant_id, release_id)


@router.post("", response_model=ReleaseRead, status_code=status.HTTP_201_CREATED)
async def create_release(
    payload: ReleaseCreate,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "publish")),
) -> Release:
    snapshot = await capture_snapshot(db, ctx.tenant_id)
    return await crud.create(db, ctx.tenant_id, payload, snapshot=snapshot, created_by=ctx.user_id)
