"""Centralized monorepo path resolution for template-library artifacts.

Why this module exists
----------------------
Before this file landed, every caller that needed to reach into the
monorepo's ``template-library/`` from inside ``apps/ab-skill/`` had to count
``..`` segments by hand. The depth differs per call site:

    skills/template-registry/scripts/registry_loader.py    → 5 × ".."
    skills/template-registry/scripts/check_contracts.py    → 3 × ".."
    skills/template-registry/video_dsl/runtime/template_binder → 6 × ".."
    skills/gen-script/scripts/gen_script.py                → 5 × ".."
    skills/render-video/scripts/render_video.py            → 4 × ".."

Five copies, five chances for an off-by-one bug, and any future directory
move silently breaks one site without touching the others. This module
computes the monorepo root **once** from its own location and exposes
helpers so callers no longer count.

All sibling skills (including the ``list_templates.py`` CLI entry, via
``registry_loader``) go through these helpers, so the monorepo-root
computation lives in exactly one place.
"""
from __future__ import annotations

import os
from typing import Optional

__all__ = ["monorepo_root", "monorepo_registry_path", "monorepo_template_src_dir"]

# This file lives at:
#   <repo>/apps/ab-skill/skills/template-registry/scripts/template_paths.py
# So the monorepo root is 5 levels up.
_HERE = os.path.dirname(os.path.abspath(__file__))
_REPO_ROOT = os.path.normpath(os.path.join(_HERE, "..", "..", "..", "..", ".."))


def monorepo_root() -> str:
    """Absolute path to the ab-platform monorepo root.

    Always returns a string; the caller is responsible for checking
    ``os.path.isdir(...)`` if the root may genuinely be absent (e.g. when
    the skill is consumed standalone via the npm package).
    """
    return _REPO_ROOT


def monorepo_registry_path() -> str:
    """Path to ``template-library/packages/metadata/registry.json``.

    Always returns the computed path even when the file does not exist —
    so callers can keep their existing ``os.path.exists(...)`` / try-load
    branches unchanged. Mirrors the historical behavior of the 4 in-tree
    helpers it replaces.
    """
    return os.path.join(_REPO_ROOT, "template-library", "packages", "metadata", "registry.json")


def monorepo_template_src_dir(template_id: str) -> Optional[str]:
    """Locate a template's source directory under ``template-library``.

    Returns the absolute path **only when the directory exists**; returns
    ``None`` for the standalone / npm-consumer case where there is no
    monorepo to reach into. Matches ``gen_script._locate_template_dir``'s
    historical contract (callers test the result for None).
    """
    if not template_id:
        return None
    tpl_dir = os.path.join(
        _REPO_ROOT, "template-library", "packages", "templates", "src", template_id
    )
    return tpl_dir if os.path.isdir(tpl_dir) else None
