#!/usr/bin/env python3
"""
cache.py - Centralized Caching for Regrow Module

WO-TOKENIZER-BRIDGE-01.1: Provides module-level caches to eliminate
repeated loading overhead in the generation loop.

Caches:
- Manifest JSON (parsed once per path)
- Base path resolution (computed once per manifest)

Usage:
    from helix_cdc.regrow.cache import get_manifest_and_base

    manifest, base_path = get_manifest_and_base("seeds/hybrid_manifest_v2.json")
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict, Tuple, Union


# Cache for parsed manifests and their resolved base paths
_MANIFEST_CACHE: Dict[str, Tuple[Dict[str, Any], Path]] = {}


def get_manifest_and_base(
    manifest_path: Union[str, Path],
) -> Tuple[Dict[str, Any], Path]:
    """
    Get cached manifest and resolved base path.

    On first access for a path, loads and parses the JSON, then resolves
    the base path for relative paths. Subsequent accesses return cached values.

    Args:
        manifest_path: Path to the manifest JSON file.

    Returns:
        (manifest_dict, base_path)
    """
    manifest_path = Path(manifest_path).absolute()
    key = str(manifest_path)

    if key not in _MANIFEST_CACHE:
        # Load manifest
        with open(manifest_path, "r") as f:
            manifest = json.load(f)

        # Determine base path
        base_path = manifest_path.parent

        # Adjust base_path if manifest uses paths like "seeds/..." relative to repo root
        if manifest.get("shards"):
            first_path = manifest["shards"][0].get("path", "")
            if first_path.startswith("seeds/") or first_path.startswith("tmp/"):
                test_base = manifest_path.parent.parent
                test_path = test_base / first_path
                if test_path.exists():
                    base_path = test_base

        _MANIFEST_CACHE[key] = (manifest, base_path)

    return _MANIFEST_CACHE[key]


def clear_manifest_cache() -> None:
    """Clear all cached manifests."""
    _MANIFEST_CACHE.clear()


def get_manifest_cache_info() -> Dict[str, Any]:
    """Get information about the manifest cache."""
    return {
        "num_cached_manifests": len(_MANIFEST_CACHE),
        "cached_paths": list(_MANIFEST_CACHE.keys()),
    }
