"""GET /governance/session/{id}/ — GSAP §5.5"""
import uuid
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlmodel import select
from gsap_broker.db import get_session
from gsap_broker.db_models import AuthorizationContextDB, CompletionReceiptDB
from gsap_broker.models import SessionResponse, ACStatus

router = APIRouter()

@router.get("/session/{context_id}/", response_model=SessionResponse, summary="View session (GSAP §5.5)")
async def session_detail(context_id: uuid.UUID, db: AsyncSession = Depends(get_session)):
    result = await db.exec(select(AuthorizationContextDB).where(AuthorizationContextDB.context_id == context_id))
    ac_db = result.first()
    if not ac_db: raise HTTPException(status_code=404, detail="Not found.")

    cr_result = await db.exec(select(CompletionReceiptDB).where(CompletionReceiptDB.context_id == context_id))
    cr_db = cr_result.first()
    cr_data = None
    if cr_db:
        cr_data = {"outcome": cr_db.outcome, "behavioral_attestation": cr_db.behavioral_attestation_status,
                   "chronicle_session_id": cr_db.chronicle_session_id, "received_at": cr_db.received_at.isoformat(),
                   "signature_verified": cr_db.signature_verified}

    return SessionResponse(
        context_id=ac_db.context_id, principal_did=ac_db.principal_did,
        accord_template=ac_db.accord_template, playbook=ac_db.playbook,
        status=ACStatus(ac_db.status), issued_at=ac_db.issued_at,
        expires_at=ac_db.expires_at, consumed_at=ac_db.consumed_at,
        chronicle_event_cid=ac_db.chronicle_event_cid or None, completion_receipt=cr_data)
