"""
Interrupt Context Enricher for Mid Platform.
[AC-MARH-03, AC-MARH-04] Interrupted segments processing and fallback handling.

Features:
- Consumes interrupted_segments from request
- Provides context for re-planning
- Fallback handling for invalid/empty interrupt data
"""

import logging
from dataclasses import dataclass
from typing import Any

from app.models.mid.schemas import InterruptedSegment

logger = logging.getLogger(__name__)


@dataclass
class InterruptContext:
    """Context derived from interrupted segments."""
    consumed: bool = False
    interrupted_content: str | None = None
    interrupted_segment_ids: list[str] | None = None
    fallback_triggered: bool = False
    fallback_reason: str | None = None


class InterruptContextEnricher:
    """
    [AC-MARH-03, AC-MARH-04] Interrupt context enricher for handling user interruption.

    This component processes interrupted_segments from the request and provides
    context for re-planning. It handles edge cases where interrupt data is
    invalid or empty, ensuring the main flow continues without disruption.
    """

    def __init__(self):
        pass

    def enrich(
        self,
        interrupted_segments: list[InterruptedSegment] | None,
        generation_id: str | None = None,
    ) -> InterruptContext:
        """
        [AC-MARH-03, AC-MARH-04] Process interrupted segments and return context.

        Args:
            interrupted_segments: List of interrupted segments from request
            generation_id: Current generation ID for matching

        Returns:
            InterruptContext with processed interrupt information
        """
        if not interrupted_segments:
            logger.debug("[AC-MARH-04] No interrupted segments provided")
            return InterruptContext(
                consumed=False,
                fallback_triggered=False,
            )

        try:
            valid_segments = [
                s for s in interrupted_segments
                if s.content and s.content.strip() and s.segment_id
            ]

            if not valid_segments:
                logger.info("[AC-MARH-04] Interrupted segments empty or invalid, using fallback")
                return InterruptContext(
                    consumed=False,
                    fallback_triggered=True,
                    fallback_reason="empty_or_invalid_segments",
                )

            interrupted_content = "\n".join(s.content for s in valid_segments)
            segment_ids = [s.segment_id for s in valid_segments]

            logger.info(
                f"[AC-MARH-03] Interrupted segments consumed: "
                f"count={len(valid_segments)}, segment_ids={segment_ids[:3]}..."
            )

            return InterruptContext(
                consumed=True,
                interrupted_content=interrupted_content,
                interrupted_segment_ids=segment_ids,
                fallback_triggered=False,
            )

        except Exception as e:
            logger.warning(f"[AC-MARH-04] Failed to process interrupted segments: {e}")
            return InterruptContext(
                consumed=False,
                fallback_triggered=True,
                fallback_reason=f"error:{str(e)[:50]}",
            )

    def build_replan_context(
        self,
        interrupt_context: InterruptContext,
        base_context: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """
        [AC-MARH-03] Build context for re-planning after interruption.

        Args:
            interrupt_context: Processed interrupt context
            base_context: Existing context to enrich

        Returns:
            Enriched context for re-planning
        """
        context = base_context.copy() if base_context else {}

        if interrupt_context.consumed and interrupt_context.interrupted_content:
            context["interrupted_content"] = interrupt_context.interrupted_content
            context["interrupted_segment_ids"] = interrupt_context.interrupted_segment_ids
            context["avoid_duplicate"] = True
            logger.debug(
                f"[AC-MARH-03] Re-plan context enriched with interrupted content: "
                f"{len(interrupt_context.interrupted_content)} chars"
            )
        elif interrupt_context.fallback_triggered:
            context["interrupt_fallback"] = True
            context["interrupt_fallback_reason"] = interrupt_context.fallback_reason
            logger.debug(
                f"[AC-MARH-04] Re-plan context marked with fallback: "
                f"{interrupt_context.fallback_reason}"
            )

        return context

    def should_skip_content(
        self,
        content: str,
        interrupt_context: InterruptContext,
    ) -> bool:
        """
        [AC-MARH-03] Check if content should be skipped to avoid duplicate.

        Args:
            content: Content to check
            interrupt_context: Processed interrupt context

        Returns:
            True if content matches interrupted content and should be skipped
        """
        if not interrupt_context.consumed or not interrupt_context.interrupted_content:
            return False

        if content.strip() in interrupt_context.interrupted_content:
            logger.info(
                f"[AC-MARH-03] Content matches interrupted segment, skipping: "
                f"{content[:50]}..."
            )
            return True

        return False
