#!/usr/bin/env python3
"""
utils/delegate_runner.py — 격리된 단일 서브에이전트 실행 래퍼

실제 LLM 호출은 하지 않음 (인터페이스만 제공).
실제 실행은 dispatch.py 또는 cokacdir를 통해 수행.
이 모듈은 실행 결과를 SubAgentResult로 구조화하여 반환하는 wrapper.
"""

from __future__ import annotations

import threading
import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from utils.delegate_controller import SubAgentResult, SubAgentTask


def run_subagent(
    task: "SubAgentTask",
    depth: int,
    interrupted: threading.Event,
    task_index: int = 0,
) -> "SubAgentResult":
    """격리된 단일 서브에이전트 실행.

    실제 LLM 호출은 하지 않음 (인터페이스만 제공).
    실제 실행은 dispatch.py 또는 cokacdir를 통해 수행.
    이 함수는 실행 결과를 구조화하여 반환하는 wrapper.

    Args:
        task: 실행할 서브에이전트 태스크
        depth: 현재 위임 깊이
        interrupted: 인터럽트 시그널 이벤트
        task_index: 배치 내 태스크 인덱스

    Returns:
        SubAgentResult: 실행 결과
    """
    # 지연 임포트로 순환 참조 방지
    from utils.delegate_controller import SubAgentResult  # noqa: PLC0415

    start_time = time.monotonic()

    # 인터럽트 선확인
    if interrupted.is_set():
        return SubAgentResult(
            task_index=task_index,
            status="interrupted",
            summary=None,
            duration_seconds=0.0,
            api_calls=0,
            error="Interrupted before start",
        )

    try:
        # 실제 LLM 호출 대신 인터페이스 계약만 수행.
        # 호출 시점 인터럽트 재확인 (짧은 polling 구간 제공)
        if interrupted.is_set():
            status = "interrupted"
            summary = None
            error: str | None = "Interrupted during execution"
        else:
            # dispatch.py / cokacdir 위임 지점 — 현재는 stub
            status = "completed"
            summary = f"[stub] goal={task.goal!r} depth={depth}"
            error = None

    except Exception as exc:  # noqa: BLE001
        status = "error"
        summary = None
        error = str(exc)

    duration = time.monotonic() - start_time

    return SubAgentResult(
        task_index=task_index,
        status=status,
        summary=summary,
        duration_seconds=duration,
        api_calls=0,
        error=error,
    )
