"""Captures a point-in-time snapshot of what's currently published/active
across the studio's design surfaces, for app/routers/releases.py::POST
/releases. This is an audit trail ("what was live, and when"), not a real
promotion/rollback pipeline — see the plan's Pillar 6 note on that scope
call. Workflows/Forms use (id, version) + is_current + status=="published";
Dashboards/Pages are single-version with the same status enum; Menus have
no publish concept, so status=="active" is their analogue."""

import uuid
from datetime import datetime, timezone

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.navigation import Dashboard, Menu, Page
from app.models.workflow import Form, Workflow


async def capture_snapshot(db: AsyncSession, tenant_id: uuid.UUID) -> dict:
    workflows = (
        await db.execute(
            select(Workflow.workflow_id, Workflow.version, Workflow.name).where(
                Workflow.tenant_id == tenant_id, Workflow.is_current.is_(True), Workflow.status == "published"
            )
        )
    ).all()
    # The live version of each form: its latest published one, even while a
    # newer draft is being edited.
    forms = (
        await db.execute(
            select(Form.form_id, Form.version, Form.name)
            .where(Form.tenant_id == tenant_id, Form.status == "published")
            .distinct(Form.form_id)
            .order_by(Form.form_id, Form.version.desc())
        )
    ).all()
    pages = (
        await db.execute(
            select(Page.id, Page.name).where(Page.tenant_id == tenant_id, Page.status == "published")
        )
    ).all()
    dashboards = (
        await db.execute(
            select(Dashboard.id, Dashboard.name).where(Dashboard.tenant_id == tenant_id, Dashboard.status == "published")
        )
    ).all()
    menus = (
        await db.execute(
            select(Menu.id, Menu.label).where(Menu.tenant_id == tenant_id, Menu.status == "active")
        )
    ).all()

    return {
        "captured_at": datetime.now(timezone.utc).isoformat(),
        "workflows": [{"workflow_id": str(w.workflow_id), "version": w.version, "name": w.name} for w in workflows],
        "forms": [{"form_id": str(f.form_id), "version": f.version, "name": f.name} for f in forms],
        "pages": [{"id": str(p.id), "name": p.name} for p in pages],
        "dashboards": [{"id": str(d.id), "name": d.name} for d in dashboards],
        "menus": [{"id": str(m.id), "label": m.label} for m in menus],
    }


def snapshot_counts(snapshot: dict) -> dict[str, int]:
    return {key: len(snapshot.get(key) or []) for key in ("workflows", "forms", "pages", "dashboards", "menus")}
