"""Citation verification implementation."""

from __future__ import annotations

from typing import TYPE_CHECKING

from noteflow.domain.summarization import CitationVerificationResult

if TYPE_CHECKING:
    from collections.abc import Sequence

    from noteflow.domain.entities import Segment, Summary


class SegmentCitationVerifier:
    """Verify that summary citations reference valid segments.

    Checks that all segment_ids in key points and action items
    correspond to actual segments in the transcript.
    """

    def verify_citations(
        self,
        summary: Summary,
        segments: Sequence[Segment],
    ) -> CitationVerificationResult:
        """Verify all segment_ids exist in the transcript.

        Args:
            summary: Summary with key points and action items to verify.
            segments: Available transcript segments.

        Returns:
            CitationVerificationResult with validation status and details.
        """
        # Build set of valid segment IDs
        valid_segment_ids = {seg.segment_id for seg in segments}

        # Track invalid citations
        invalid_key_point_indices: list[int] = []
        invalid_action_item_indices: list[int] = []
        missing_segment_ids: set[int] = set()

        # Verify key points
        for idx, key_point in enumerate(summary.key_points):
            for seg_id in key_point.segment_ids:
                if seg_id not in valid_segment_ids:
                    if idx not in invalid_key_point_indices:
                        invalid_key_point_indices.append(idx)
                    missing_segment_ids.add(seg_id)

        # Verify action items
        for idx, action_item in enumerate(summary.action_items):
            for seg_id in action_item.segment_ids:
                if seg_id not in valid_segment_ids:
                    if idx not in invalid_action_item_indices:
                        invalid_action_item_indices.append(idx)
                    missing_segment_ids.add(seg_id)

        is_valid = not invalid_key_point_indices and not invalid_action_item_indices

        return CitationVerificationResult(
            is_valid=is_valid,
            invalid_key_point_indices=tuple(invalid_key_point_indices),
            invalid_action_item_indices=tuple(invalid_action_item_indices),
            missing_segment_ids=tuple(sorted(missing_segment_ids)),
        )

    def filter_invalid_citations(
        self,
        summary: Summary,
        segments: Sequence[Segment],
    ) -> Summary:
        """Return a copy of the summary with invalid citations removed.

        Invalid segment_ids are removed from key points and action items.
        Items with no remaining citations keep empty segment_ids lists.

        Args:
            summary: Summary to filter.
            segments: Available transcript segments.

        Returns:
            New Summary with invalid citations removed.
        """
        valid_segment_ids = {seg.segment_id for seg in segments}

        # Filter key point citations
        from noteflow.domain.entities import ActionItem, KeyPoint
        from noteflow.domain.entities import Summary as SummaryEntity

        filtered_key_points = [
            KeyPoint(
                text=kp.text,
                segment_ids=[sid for sid in kp.segment_ids if sid in valid_segment_ids],
                start_time=kp.start_time,
                end_time=kp.end_time,
                db_id=kp.db_id,
            )
            for kp in summary.key_points
        ]

        # Filter action item citations
        filtered_action_items = [
            ActionItem(
                text=ai.text,
                assignee=ai.assignee,
                due_date=ai.due_date,
                priority=ai.priority,
                segment_ids=[sid for sid in ai.segment_ids if sid in valid_segment_ids],
                db_id=ai.db_id,
            )
            for ai in summary.action_items
        ]

        return SummaryEntity(
            meeting_id=summary.meeting_id,
            executive_summary=summary.executive_summary,
            key_points=filtered_key_points,
            action_items=filtered_action_items,
            generated_at=summary.generated_at,
            provider_name=summary.provider_name,
            model_name=summary.model_name,
            tokens_used=summary.tokens_used,
            latency_ms=summary.latency_ms,
            verification=summary.verification,
            db_id=summary.db_id,
        )
