"""Interview tool for interactive user questioning.

Provides an AskUserQuestion-style tool that pauses agent execution
and presents an interactive multi-choice questionnaire in the TUI.

The tool uses LangGraph's interrupt() mechanism to pause the graph,
allowing the TUI to render an interactive widget and collect user answers.
"""

from __future__ import annotations

import json
from typing import Any

from langchain_core.tools import tool

# Import interrupt from langgraph for pausing execution
try:
    from langgraph.types import interrupt
except ImportError:
    # Fallback: if langgraph is not available, just return empty
    def interrupt(value: Any) -> Any:  # type: ignore[misc]
        """Fallback interrupt that returns empty dict."""
        return {}


@tool
def ask_user_question(
    questions: list[dict[str, Any]],
) -> str:
    """Ask the user one or more clarifying questions before proceeding.

    Use this tool when you need to gather user preferences, clarify ambiguous
    instructions, or get decisions on implementation choices. The questions are
    presented as an interactive form in the terminal.

    Args:
        questions: List of question objects. Each question has:
            - question (str): The complete question to ask the user.
            - header (str): Short label for the tab (max 12 chars). E.g., "데이터 타입"
            - options (list[dict]): 2-4 available choices. Each option has:
                - label (str): Display text (1-5 words). E.g., "Redis"
                - description (str): Explanation of the option. E.g., "인메모리 데이터 스토어"
            - multi_select (bool): If true, user can select multiple options. Default: false.

    Returns:
        JSON string with user's answers. Each answer maps the question header
        to the selected option label(s) or custom text input.

    Example:
        ask_user_question(questions=[
            {
                "question": "어떤 캐싱 전략을 사용할까요?",
                "header": "캐싱 전략",
                "options": [
                    {"label": "Redis", "description": "인메모리 데이터 스토어, 고성능"},
                    {"label": "Memcached", "description": "분산 메모리 캐싱 시스템"},
                    {"label": "로컬 캐시", "description": "애플리케이션 내 메모리 캐시"},
                ],
                "multi_select": false,
            }
        ])
    """
    # Validate questions format
    validated_questions = []
    for q in questions:
        validated_q = {
            "question": str(q.get("question", "")),
            "header": str(q.get("header", "질문"))[:12],
            "options": [],
            "multi_select": bool(q.get("multi_select", False)),
        }
        for opt in q.get("options", []):
            validated_q["options"].append({
                "label": str(opt.get("label", "")),
                "description": str(opt.get("description", "")),
            })
        validated_questions.append(validated_q)

    if not validated_questions:
        return json.dumps({"error": "No questions provided"}, ensure_ascii=False)

    # Interrupt execution and wait for user answers
    # The TUI will render an InterviewWidget and resume with the answers
    answers = interrupt({
        "type": "ask_user_question",
        "questions": validated_questions,
    })

    # Format answers for the agent
    if isinstance(answers, dict):
        return json.dumps(answers, ensure_ascii=False, indent=2)
    return json.dumps({"raw": str(answers)}, ensure_ascii=False)
