"""Governance 서비스 — 감사 기록 + 승인 요청 통합."""

import logging

from sentinel.audit import audit_log
from sentinel.schema import AuditEvent, ApprovalRequest

logger = logging.getLogger("sentinel.governance")


class GovernanceService:
    """모든 surface(Web/MCP/CLI)에서 동일한 감사·승인 경로를 보장합니다."""

    def record_action(self, event: AuditEvent) -> str:
        """감사 로그에 이벤트를 기록합니다. audit row id(문자열)를 반환합니다."""
        audit_log.log(
            action=event.action,
            tool_name=event.action_type.value,
            is_mutation=event.is_mutation,
            status=event.status,
            error=event.error,
            metadata={
                "actor": event.actor,
                "surface": event.surface.value,
                "target_refs": event.target_refs,
                **(event.metadata or {}),
            },
        )
        logger.info(
            "audit: %s [%s] by %s via %s",
            event.action,
            event.action_type.value,
            event.actor,
            event.surface.value,
        )
        return event.action

    def require_approval(self, req: ApprovalRequest) -> str:
        """승인 요청을 생성하고 audit에도 기록합니다. approval_id를 반환합니다."""
        from sentinel.approval import approval_manager

        approval_id = approval_manager.request_approval(
            request_type=req.request_type,
            action_summary=req.action_summary,
            params=req.params,
        )

        self.record_action(AuditEvent(
            action=f"approval_requested:{req.request_type}",
            action_type=req.surface,
            actor=req.actor,
            surface=req.surface,
            target_refs=req.evidence_refs,
            is_mutation=False,
            status="pending",
        ))

        return approval_id


# 모듈 레벨 싱글턴
governance = GovernanceService()
