"""Worktree path resolver — task_id로부터 활성 worktree 디렉토리를 탐지.

codex_gate_check.py 등 외부 검증 도구가 main 브랜치가 아닌 진행 중인
worktree의 실제 변경분을 읽도록 돕는다.
"""
import json
import logging
import os
from pathlib import Path

logger = logging.getLogger("worktree_resolver")

DEFAULT_TASK_TIMERS = "/home/jay/workspace/memory/task-timers.json"
DEFAULT_PROJECTS_ROOT = "/home/jay/projects"


def _load_task_timers(path: str) -> dict:
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception as e:
        logger.warning("task-timers.json load failed: %s", e)
        return {}


def resolve_worktree_target_dir(
    task_id: str | None,
    *,
    task_timers_path: str = DEFAULT_TASK_TIMERS,
    projects_root: str = DEFAULT_PROJECTS_ROOT,
) -> tuple[str | None, str]:
    """task_id에서 worktree 디렉토리 경로를 탐지.

    Returns:
        (path, source) — path가 None이면 worktree 없음.
        source: "task_timers" | "glob" | "none"

    탐지 순서:
      1. task-timers.json[task_id].worktree_path (있고 .worktrees 경로면)
      2. {projects_root}/*/.worktrees/{task_id}-* (최근 수정된 것)
      3. (None, "none")
    """
    if not task_id:
        return None, "none"

    # 1. task-timers.json
    timers = _load_task_timers(task_timers_path)
    task_entry = timers.get("tasks", {}).get(task_id, {})
    explicit = task_entry.get("worktree_path")
    if explicit and os.path.isdir(explicit) and "/.worktrees/" in explicit:
        logger.info("worktree resolved via task-timers: %s", explicit)
        return explicit, "task_timers"

    # 2. glob fallback
    candidates: list[Path] = []
    projects = Path(projects_root)
    if projects.is_dir():
        for project_dir in projects.iterdir():
            wt_root = project_dir / ".worktrees"
            if not wt_root.is_dir():
                continue
            for wt in wt_root.glob(f"{task_id}-*"):
                if wt.is_dir():
                    candidates.append(wt)
    if candidates:
        latest = max(candidates, key=lambda p: p.stat().st_mtime)
        logger.info("worktree resolved via glob: %s", latest)
        return str(latest), "glob"

    return None, "none"
