"""RunManifest builder — snapshots the environment at the start of a run.

The ``env_fingerprint`` dict records the dimensions that (a) actually affect
how a run behaves and (b) are cheap to compute. A replay-time diff against
the original fingerprint tells us whether the environment drifted enough
to invalidate a comparison.

We deliberately avoid hashing file contents (O(files × size)). Mtime + size
over a small set of directories (identity, skills) is fast, deterministic,
and catches every real change in practice. The storage helpers already
cache for 5 minutes (see ``evolution.storage.env_fingerprint``).
"""

from __future__ import annotations

from typing import Any

from agntspace.evolution.schemas import (
    POLICY_INCUMBENT_DEFAULT,
    RunManifest,
    new_run_id,
)
from agntspace.evolution.storage import env_fingerprint


def build_run_manifest(
    *,
    skill_name: str,
    agent_name: str,
    caller: str = "system",
    trigger_type: str = "",
    correlation_id: str = "",
    parent_run_id: str = "",
    policy_id: str = POLICY_INCUMBENT_DEFAULT,
    model_name: str = "",
    model_tier: str = "",
    vault_reader: Any | None = None,
    graph: Any | None = None,
    registry: Any | None = None,
    settings: Any | None = None,
) -> RunManifest:
    """Construct a ``RunManifest`` with a fresh run_id and env snapshot.

    Any None data source degrades to ``"unknown"`` in the fingerprint —
    the manifest is built to be non-fatal. ``trigger_type`` defaults to
    ``skill_name`` when not supplied (they're usually the same).
    """
    fp = env_fingerprint(
        vault_reader=vault_reader,
        graph=graph,
        registry=registry,
        settings=settings,
    )
    return RunManifest(
        run_id=new_run_id(),
        correlation_id=correlation_id,
        parent_run_id=parent_run_id,
        caller=caller,
        trigger_type=trigger_type or skill_name,
        skill_name=skill_name,
        agent_name=agent_name,
        policy_id=policy_id,
        model_name=model_name,
        model_tier=model_tier,
        env_fingerprint=fp,
    )
