"""
Review orchestrator for Gar
리뷰 모드에 따라 적절한 에이전트를 실행
"""

from __future__ import annotations

from pathlib import Path
from typing import Iterable

from common.context import (
    ReviewConfig,
    ReviewContext,
    ReviewFinding,
    ReviewFlags,
    ReviewMode,
    ReviewReport,
    ReviewState,
    ReviewTarget,
)
from interface.llm.client import LocalOpenAIAgentBackend
from interface.reviewers.interface.agent import InterfaceReviewAgent


class ReviewOrchestrator:
    """리뷰 모드에 따라 적절한 에이전트를 실행하는 오케스트레이터"""

    def __init__(self, backend: LocalOpenAIAgentBackend | None = None, base_url: str | None = None) -> None:
        self._backend = backend or LocalOpenAIAgentBackend(base_url=base_url)

    def build_context(
        self,
        *,
        mode: ReviewMode,
        files: Iterable[str | Path],
        model: str,
        temperature: float,
        max_output_tokens: int,
        max_retries: int,
        language: str | None,
        quiet: bool = False,
        show_prompt: bool = False,
        input_context: dict | None = None,
    ) -> ReviewContext:
        target_files = [Path(f).resolve() for f in files]
        config = ReviewConfig(
            model=model,
            temperature=temperature,
            max_output_tokens=max_output_tokens,
            max_retries=max_retries,
            language=language,
        )
        flags = ReviewFlags(quiet=quiet, show_prompt=show_prompt)
        target = ReviewTarget(files=target_files)
        state = ReviewState(input_context=input_context)
        return ReviewContext(mode=mode, config=config, flags=flags, target=target, state=state)

    def run(self, ctx: ReviewContext) -> ReviewReport:
        """컨텍스트에 따라 적절한 에이전트 실행 (INTERFACE 모드 전용)"""

        if ctx.mode is not ReviewMode.INTERFACE:
            raise ValueError(f"interface orchestrator는 INTERFACE 모드만 지원합니다. 현재 모드: {ctx.mode.value}")

        agent = InterfaceReviewAgent(self._backend)
        findings = agent.run(ctx)

        # 방어 로직: 빈 결과 방지
        if not findings:
            findings = [
                ReviewFinding(
                    file=None,
                    line=None,
                    category="system",
                    severity="info",
                    message="리뷰가 완료되었으나 발견된 문제가 없습니다.",
                )
            ]

        return ReviewReport(mode=ctx.mode, findings=findings)