"""Performance 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 performance.display import build_performance_panel
from performance.main import run_performance_mode_analysis, run_performance_mode_from_input_context

if TYPE_CHECKING:
    from common.config import GarConfig

logger = logging.getLogger(__name__)

logging.basicConfig(
    level=logging.WARNING,  # INFO 로그를 stdout에 출력하지 않음
    format="%(message)s",
    force=True,
)


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",
    quiet: bool = False,
) -> int:
    """Execute performance mode analysis.

    Args:
        input_context: Prebuilt input context (optional)
        file_list: List of files to review (review_scope="all"에서 사용)
        config: Configuration dictionary (unused)
        model: Model name to use (unused, from env)
        review_scope: Review scope selection ("staged" or "all")
        quiet: Whether to suppress output

    Returns:
        Exit code (0 for success, 1 for failure)
    """
    handle = None
    try:
        if not quiet:
            handle = input_context.get("_ui_handle") if input_context else start_progress("성능 분석 모드")

        if input_context:
            # progress handle 초기화 (file_entries 개수 기준, 하지만 실제로는 suspicious_regions의 고유 파일 개수 사용)
            if not quiet:
                handle = input_context.get("_ui_handle") or start_progress("성능 분석 모드", total_files=0)
                input_context["_ui_handle"] = handle
            else:
                handle = input_context.get("_ui_handle")
            
            _maybe_update_status(handle, "AST 분석 및 LLM 검토 중")
            result = run_performance_mode_from_input_context(input_context, top_percent=10, progress_handle=handle)
        else:
            # file_list를 결정한 후 progress handle 초기화
            if not quiet:
                if file_list:
                    handle = start_progress("성능 분석 모드", total_files=len(file_list))
                else:
                    handle = start_progress("성능 분석 모드", total_files=0)
            
            _maybe_update_status(handle, "AST 분석 및 LLM 검토 중")
            result = run_performance_mode_analysis(
                review_scope=review_scope,
                file_list=file_list,
                top_percent=10,
                progress_handle=handle,
            )

        if not quiet:
            _maybe_update_status(handle, "결과 파싱/렌더링 중")
            panel = build_performance_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.info("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
