"""Normal mode runner."""

from __future__ import annotations

import logging
from pathlib import Path
from typing import TYPE_CHECKING

from common.ui import console, finish_progress, start_progress, update_status
from normal.display import build_normal_panel
from normal.main import run_normal_mode_analysis, run_normal_mode_from_input_context

if TYPE_CHECKING:
    from common.config import GarConfig

logger = logging.getLogger(__name__)


def _maybe_update_status(handle, text: str) -> None:
    if handle:
        update_status(handle, text)


def _maybe_finish_progress(handle) -> None:
    if handle:
        finish_progress(handle)


def run(
    input_context: dict | None = None,
    *,
    file_list: list[Path] | None = None,
    config: GarConfig | None = None,
    model: str | None = None,
    review_scope: str = "staged",
    chunking_mode: str = "fast",
) -> int:
    """Execute normal mode analysis.

    Args:
        input_context: Prebuilt input context (optional)
        file_list: List of files to review (review_scope="all"에서 사용)
        config: Configuration dictionary
        model: Model name to use
        review_scope: Review scope selection ("staged" or "all")
        chunking_mode: Chunking strategy ("fast" or "thinking")

    Returns:
        Exit code (0 for success, 1 for failure)
    """
    handle = None
    try:
        logger.debug(f"Normal mode: review_scope={review_scope}, chunking_mode={chunking_mode}")

        handle = input_context.get("_ui_handle") if input_context else start_progress("일반 분석 모드")

        if input_context:
            # input_context에서 chunking_mode 가져오기
            chunking_mode = input_context.get("chunking_mode", chunking_mode)
            logger.debug(f"Normal mode: using input_context, chunking_mode={chunking_mode}")
            
            # progress handle 초기화 (file_entries 개수 기준)
            file_entries = input_context.get("files", [])
            handle = input_context.get("_ui_handle") or start_progress("일반 분석 모드", total_files=len(file_entries))
            input_context["_ui_handle"] = handle
            
            _maybe_update_status(handle, "LLM 생성 중")
            logger.debug(f"Normal mode: using input_context, chunking_mode={chunking_mode}")
            _maybe_update_status(handle, "LLM 호출 중")
            result = run_normal_mode_from_input_context(input_context, max_iterations=50)
        else:
            logger.debug(
                f"Normal mode: using direct params, review_scope={review_scope}, file_list={len(file_list) if file_list else 0} files, chunking_mode={chunking_mode}"
            )
            # file_list를 결정한 후 progress handle 초기화
            if file_list:
                handle = start_progress("일반 분석 모드", total_files=len(file_list))
            else:
                handle = start_progress("일반 분석 모드", total_files=0)
            
            _maybe_update_status(handle, "LLM 생성 중")
            result = run_normal_mode_analysis(
                max_iterations=50,
                review_scope=review_scope,
                file_list=file_list,
                chunking_mode=chunking_mode,
                progress_handle=handle,
            )
        
        logger.debug(f"Normal mode: result status={result.get('status')}")

        _maybe_update_status(handle, "결과 파싱/렌더링 중")
        panel = build_normal_panel(result)
        _maybe_finish_progress(handle)
        console.print(panel)

        return 0 if result.get("status") == "success" else 1
        
    except KeyboardInterrupt:
        _maybe_finish_progress(handle)
        console.print("[yellow]⚠ 사용자에 의해 중단되었습니다.[/yellow]")
        logger.debug("Analysis interrupted by user")
        return 1
    except Exception as e:
        _maybe_finish_progress(handle)
        console.print(f"[red]✗ 예상치 못한 오류가 발생했습니다: {str(e)}[/red]")
        logger.error(f"Unexpected error in runner: {e}", exc_info=True)
        return 1