"""Shared CLI helpers for website companion handoff commands."""
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[2]
DEFAULT_WEBSITE_ROOT = Path("/home/agent/projects/TrueTraceShorts_WebSite")


def print_json(payload: dict[str, Any]) -> None:
    print(json.dumps(payload, indent=2, ensure_ascii=False))


def find_review_package(candidate_id: str, explicit: str | None = None) -> Path:
    if explicit:
        path = Path(explicit)
        if not path.exists():
            raise FileNotFoundError(path)
        return path
    candidates = []
    for path in (ROOT / "data" / "post_candidates").glob("**/review_package*.json"):
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            continue
        if data.get("candidate_id") == candidate_id or candidate_id in str(path):
            candidates.append(path)
    if not candidates:
        raise FileNotFoundError(f"No review package found for candidate_id={candidate_id}")
    return sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True)[0]


def find_companion_spec(candidate_id: str, explicit: str | None = None) -> Path:
    if explicit:
        path = Path(explicit)
        if not path.exists():
            raise FileNotFoundError(path)
        return path
    specs = list((ROOT / "data" / "website_companion_specs").glob(f"{candidate_id}.json"))
    specs.extend((ROOT / "data" / "website_companion_specs").glob(f"{candidate_id.replace('_', '-')}.json"))
    if not specs:
        for path in (ROOT / "data" / "website_companion_specs").glob("*.json"):
            if candidate_id in path.stem:
                specs.append(path)
    if not specs:
        raise FileNotFoundError(f"No website companion spec found for candidate_id={candidate_id}")
    return sorted(set(specs))[0]
