"""
Permission Checker - Tiered governance enforcement.

Hybrid governance (Model C):
- Tier 1 (core): 2 approvals required from governance team
- Tier 2 (domain): 1 approval from domain team
- Tier 3 (free): 0 approvals (auto-approve)
"""

from __future__ import annotations

from pycharter.wiki.ontology.models import ConceptTier


class PermissionChecker:
    """
    Enforces tiered governance rules for ontology edits.

    Args:
        governance_team: List of users in the governance team
        domain_teams: Mapping of domain name to list of team members
    """

    def __init__(
        self,
        governance_team: list[str] | None = None,
        domain_teams: dict | None = None,
    ):
        self._governance_team = set(governance_team or [])
        self._domain_teams = {k: set(v) for k, v in (domain_teams or {}).items()}

    def can_edit(self, user: str, tier: ConceptTier) -> bool:
        """
        Check if a user can edit concepts at a given tier.

        Tier 1 (core): Only governance team members
        Tier 2 (domain): Governance team or domain team members
        Tier 3 (free): Anyone

        Args:
            user: Username
            tier: Concept governance tier

        Returns:
            True if the user can edit
        """
        if tier == ConceptTier.FREE:
            return True
        if tier == ConceptTier.CORE:
            return user in self._governance_team
        if tier == ConceptTier.DOMAIN:
            if user in self._governance_team:
                return True
            return any(user in members for members in self._domain_teams.values())
        return False

    def can_approve(self, user: str, tier: ConceptTier) -> bool:
        """
        Check if a user can approve proposals at a given tier.

        Same rules as can_edit: only authorized users can approve.

        Args:
            user: Username
            tier: Concept governance tier

        Returns:
            True if the user can approve
        """
        return self.can_edit(user, tier)

    def get_required_approvals(self, tier: ConceptTier) -> int:
        """
        Get the number of approvals required for a tier.

        Tier 1 (core): 2 approvals
        Tier 2 (domain): 1 approval
        Tier 3 (free): 0 approvals

        Args:
            tier: Concept governance tier

        Returns:
            Number of approvals required
        """
        if tier == ConceptTier.CORE:
            return 2
        if tier == ConceptTier.DOMAIN:
            return 1
        return 0
