# ============================================================
# src/accountable_record/stage_070_resolution/resolve.py
# ============================================================
"""Resolve stage 070 manifest directives.

WHY:
    Stage 070 may validate lock material for target Accountable Record
    repositories, but implementation repositories may explicitly opt out. This
    module reads the repository manifest and resolves whether locks are expected.

OBS:
    This module only resolves configuration. It does not load lock files, build
    graphs, verify exports, emit diagnostics, or mutate pipeline state.
"""

from dataclasses import dataclass
from pathlib import Path
import tomllib

from accountable_record.boundary.toml import is_table
from accountable_record.stage_070_resolution.base import constants


@dataclass(frozen=True)
class ResolutionDirective:
    """Resolved resolution/lock directive from the target repository manifest.

    Attributes:
        locks_path: Repository-relative lock root path when locks are expected.
    """

    locks_path: str


def resolve_resolution_directive(repo_root: Path) -> ResolutionDirective:
    """Resolve the target repository's resolution/lock directive.

    Behavior:
        - [resolution].locks = "none" opts out.
        - [resolution].locks = "<path>" declares a lock root path.
        - absent [resolution] or absent locks key defaults to data/locks.

    Args:
        repo_root: Target repository root.

    Returns:
        Resolved directive.
    """
    manifest = _read_manifest(repo_root)
    resolution = manifest.get(constants.MANIFEST_RESOLUTION_TABLE)

    if not is_table(resolution):
        return ResolutionDirective(
            locks_path=constants.LOCKS_DIRNAME,
        )

    locks_value = resolution.get(constants.MANIFEST_LOCKS_KEY)
    if locks_value == constants.LOCKS_NONE:
        return ResolutionDirective(
            locks_path=constants.LOCKS_DIRNAME,
        )

    if isinstance(locks_value, str) and locks_value.strip():
        return ResolutionDirective(
            locks_path=locks_value.strip().rstrip("/"),
        )

    return ResolutionDirective(
        locks_path=constants.LOCKS_DIRNAME,
    )


def _read_manifest(repo_root: Path) -> dict[str, object]:
    """Read SE_MANIFEST.toml if present, else return an empty manifest.

    OBS:
        Earlier stages own manifest presence and identity validation. Stage 070
        only needs directive resolution, so absence falls back to default
        lock expectations rather than creating a second manifest diagnostic.
    """
    manifest_path = repo_root / "SE_MANIFEST.toml"
    if not manifest_path.is_file():
        return {}

    with manifest_path.open("rb") as handle:
        data = tomllib.load(handle)

    if not is_table(data):
        return {}

    return data
