"""
Review Workflow - Submit reviews and check approval status.

Reviews are decisions (approve/request_changes/reject) on proposals,
supporting the tiered governance workflow.
"""

from __future__ import annotations

import uuid
from typing import Any

from pycharter.wiki.shared.errors import CollaborationError


class ReviewWorkflow:
    """
    Manages review workflow for proposals.

    Args:
        session: SQLAlchemy session
    """

    def __init__(self, session=None):
        self._session = session

    def _require_session(self):
        if self._session is None:
            raise CollaborationError("No database session configured")

    def submit_review(
        self,
        proposal_id: str,
        reviewer: str,
        decision: str,
        comment: str | None = None,
    ) -> str:
        """
        Submit a review on a proposal.

        Args:
            proposal_id: UUID of the proposal
            reviewer: Reviewer name
            decision: One of 'approve', 'request_changes', 'reject'
            comment: Optional review comment

        Returns:
            UUID string of the created review
        """
        self._require_session()

        valid_decisions = {"approve", "request_changes", "reject"}
        if decision not in valid_decisions:
            raise CollaborationError(
                f"Invalid decision '{decision}'. Must be one of: {sorted(valid_decisions)}"
            )

        from pycharter.db.models.wiki.review import ReviewModel

        review = ReviewModel(
            proposal_id=uuid.UUID(proposal_id),
            reviewer=reviewer,
            decision=decision,
            comment=comment,
        )
        self._session.add(review)
        self._session.flush()
        return str(review.id)

    def get_reviews(self, proposal_id: str) -> list[dict[str, Any]]:
        """
        Get all reviews for a proposal.

        Args:
            proposal_id: UUID of the proposal

        Returns:
            List of review dicts
        """
        self._require_session()

        from pycharter.db.models.wiki.review import ReviewModel

        rows = (
            self._session.query(ReviewModel)
            .filter(ReviewModel.proposal_id == uuid.UUID(proposal_id))
            .all()
        )
        return [
            {
                "id": str(row.id),
                "proposal_id": str(row.proposal_id),
                "reviewer": row.reviewer,
                "decision": row.decision,
                "comment": row.comment,
                "created_at": str(row.created_at) if row.created_at else None,
            }
            for row in rows
        ]

    def check_approval_status(
        self, proposal_id: str, required_approvals: int = 1
    ) -> dict[str, Any]:
        """
        Check if a proposal has enough approvals.

        Args:
            proposal_id: UUID of the proposal
            required_approvals: Number of approvals needed

        Returns:
            Dict with 'approved', 'approval_count', 'rejection_count'
        """
        self._require_session()

        reviews = self.get_reviews(proposal_id)
        approvals = [r for r in reviews if r["decision"] == "approve"]
        rejections = [r for r in reviews if r["decision"] == "reject"]

        return {
            "approved": len(approvals) >= required_approvals and len(rejections) == 0,
            "approval_count": len(approvals),
            "rejection_count": len(rejections),
            "required_approvals": required_approvals,
        }
