"""task-key → (task_root, project_root) 해석 공유 헬퍼.

read-side CLI(context-cost, error-report)가 동일한 입력 계약을 공유하기 위한
SSOT. target 은 task-root 경로 / task-key 둘 다 받는다.
"""
from __future__ import annotations

from pathlib import Path

from okstra_project import (
    ResolverError,
    StateError,
    find_task_root,
    resolve_project_root,
)

# 순수 경로 계산은 paths 가 소유한다. 여기 있는 동안 stage_map·stage_ledger 가
# 그 함수 하나 때문에 이 모듈을 거쳐 okstra_project 전체를 끌어왔다.
from .paths import infer_project_root, project_rel  # noqa: F401 — 재노출


def resolve_task_root(target: str, project_root: str, cwd: str) -> tuple[Path, Path]:
    target_path = Path(target).expanduser()
    if target_path.exists():
        task_root = target_path.resolve()
        return task_root, infer_project_root(task_root)

    try:
        resolved_project = Path(
            resolve_project_root(explicit_root=project_root, cwd=cwd)
        ).resolve()
    except ResolverError as exc:
        raise SystemExit(f"project root resolution failed: {exc}") from exc

    try:
        task_root = find_task_root(resolved_project, target)
    except StateError as exc:
        raise SystemExit(
            f"target is neither an existing path nor a valid task-key: "
            f"{target!r} ({exc})"
        ) from exc
    if task_root is None:
        raise SystemExit(f"no task root for task key: {target}")
    return task_root.resolve(), resolved_project


