"""Review workflow for Beaver skill drafts."""

from __future__ import annotations

from uuid import uuid4

from beaver.skills.specs import SkillDraft, SkillReviewRecord, SkillReviewState, SkillSpecStore


class ReviewService:
    def __init__(self, store: SkillSpecStore) -> None:
        self.store = store

    def submit_for_review(self, skill_name: str, draft_id: str, reviewer_request: str, requested_by: str = "system") -> SkillReviewRecord:
        draft = self._require_draft(skill_name, draft_id)
        draft.status = SkillReviewState.IN_REVIEW.value
        self.store.write_draft(draft)
        review = SkillReviewRecord(
            review_id=uuid4().hex,
            draft_id=draft_id,
            skill_name=skill_name,
            requested_at=_utc_now(),
            requested_by=requested_by,
            status=SkillReviewState.IN_REVIEW.value,
            notes=reviewer_request,
        )
        self.store.write_review(review)
        return review

    def approve(self, skill_name: str, draft_id: str, reviewer: str, notes: str = "") -> SkillReviewRecord:
        draft = self._require_draft(skill_name, draft_id)
        draft.status = SkillReviewState.APPROVED.value
        self.store.write_draft(draft)
        review = SkillReviewRecord(
            review_id=uuid4().hex,
            draft_id=draft_id,
            skill_name=skill_name,
            requested_at=_utc_now(),
            requested_by=reviewer,
            status=SkillReviewState.APPROVED.value,
            reviewer=reviewer,
            reviewed_at=_utc_now(),
            notes=notes,
        )
        self.store.write_review(review)
        return review

    def reject(self, skill_name: str, draft_id: str, reviewer: str, notes: str = "") -> SkillReviewRecord:
        draft = self._require_draft(skill_name, draft_id)
        review = SkillReviewRecord(
            review_id=uuid4().hex,
            draft_id=draft_id,
            skill_name=skill_name,
            requested_at=_utc_now(),
            requested_by=reviewer,
            status=SkillReviewState.REJECTED.value,
            reviewer=reviewer,
            reviewed_at=_utc_now(),
            notes=notes,
        )
        self.store.write_review(review)
        self.store.delete_draft(skill_name, draft_id)
        return review

    def _require_draft(self, skill_name: str, draft_id: str) -> SkillDraft:
        draft = self.store.read_draft(skill_name, draft_id)
        if draft is None:
            raise ValueError(f"Draft not found: {skill_name}/{draft_id}")
        return draft


def _utc_now() -> str:
    from datetime import datetime, timezone

    return datetime.now(timezone.utc).isoformat()
