"""Stateless storyboard/script/bible loaders for client projects."""

import json
import logging
from recoil.core.paths import projects_root, ProjectPaths

logger = logging.getLogger(__name__)


def _state_dir(project):
    return ProjectPaths.for_project(project).visual_state_dir


def load_client_storyboard(project, episode=1):
    plan_path = _state_dir(project) / "plans" / f"ep_{episode:03d}_plan.json"
    if not plan_path.exists():
        raise FileNotFoundError(f"Client plan not found: {plan_path}")
    data = json.loads(plan_path.read_text(encoding="utf-8"))
    data["_source"] = "manifest"
    return data


def load_client_bible(project):
    bible_path = _state_dir(project) / "client_bible.json"
    if not bible_path.exists():
        raise FileNotFoundError(f"Client bible not found: {bible_path}")
    data = json.loads(bible_path.read_text(encoding="utf-8"))
    data["_source"] = "client_bible"
    return data


def load_client_project_config(project):
    config_path = projects_root() / project / "project_config.json"
    if not config_path.exists():
        raise FileNotFoundError(f"Client project config not found: {config_path}")
    data = json.loads(config_path.read_text(encoding="utf-8"))
    return data


def save_client_bible(project, bible_data):
    bible_path = _state_dir(project) / "client_bible.json"
    bible_path.parent.mkdir(parents=True, exist_ok=True)
    bible_path.write_text(json.dumps(bible_data, indent=2, ensure_ascii=False), encoding="utf-8")
    logger.info("Saved client bible: %s", bible_path)


def get_client_refs_dir(project):
    """DEPRECATED (audit F4, 2026-06-10). v1 'output/refs/' no longer exists;
    refs live under assets/{char,loc,prop}/<slug>/<look>/; hero refs are direct
    files there, and pool refs live under pool/<kind>/. Read through
    ProjectPaths.resolve_ref / resolve_hero — the canonical ref monopoly.
    """
    from recoil.core.paths import DeprecatedPathAPIError

    raise DeprecatedPathAPIError(
        "get_client_refs_dir() returned the dead v1 output/refs/ path. "
        "Use ProjectPaths.for_project(project).resolve_ref(...) instead."
    )
