"""Interview flow handler mixin for IeumApp."""
# ruff: noqa: BLE001, PLR0912, PLR2004, S110

from __future__ import annotations

import asyncio
import uuid
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    pass


class InterviewHandlerMixin:
    """Interview flow methods for IeumApp."""

    async def _request_interview(
        self,
        questions: list[dict[str, Any]],
    ) -> asyncio.Future:
        """Request user answers via interactive interview widget.

        Mounts InterviewWidget inline in the messages area.
        Returns a Future that resolves to the user's answers dict.

        Uses a separate tracking variable (_pending_interview_widget) to
        avoid conflicts if both an approval and interview arrive simultaneously.
        """
        from ieum.widgets.interview import InterviewWidget

        from textual.containers import Container

        loop = asyncio.get_running_loop()
        result_future: asyncio.Future = loop.create_future()

        # If there's already a pending interview, wait for it to complete first
        if self._pending_interview_widget is not None:
            timeout = 300  # 5 minutes
            elapsed = 0.0
            while self._pending_interview_widget is not None:  # noqa: ASYNC110
                await asyncio.sleep(0.1)
                elapsed += 0.1
                if elapsed > timeout:
                    if self._pending_interview_widget:
                        try:
                            self._pending_interview_widget.remove()
                        except Exception:
                            pass
                        self._pending_interview_widget = None
                    break

        unique_id = f"interview-{uuid.uuid4().hex[:8]}"
        widget = InterviewWidget(questions, id=unique_id)
        widget.set_future(result_future)

        # Store reference in dedicated interview tracker
        self._pending_interview_widget = widget

        try:
            messages = self.query_one("#messages", Container)
            await messages.mount(widget)
            self.call_after_refresh(widget.scroll_visible)
            self.call_after_refresh(widget.focus)
        except Exception as e:
            self._pending_interview_widget = None
            if not result_future.done():
                result_future.set_exception(e)

        return result_future

    async def on_interview_widget_answered(
        self,
        event: Any,  # noqa: ANN401, ARG002
    ) -> None:
        """Handle interview widget submission - remove and refocus input."""
        if self._pending_interview_widget:
            await self._pending_interview_widget.remove()
            self._pending_interview_widget = None

        if self._chat_input:
            self.call_after_refresh(self._chat_input.focus_input)

    async def on_interview_widget_cancelled(
        self,
        event: Any,  # noqa: ANN401, ARG002
    ) -> None:
        """Handle interview widget cancellation - remove and refocus input."""
        if self._pending_interview_widget:
            await self._pending_interview_widget.remove()
            self._pending_interview_widget = None

        if self._chat_input:
            self.call_after_refresh(self._chat_input.focus_input)
