"""Neutral discovery of the frozen ARR deterministic processor identity."""

from __future__ import annotations

import importlib.util
import sys
from pathlib import Path

from arr_ingestion.validation import ProcessorPolicy


def load_processor_policy(project_root: Path) -> ProcessorPolicy:
    skill_root = (project_root / "arr-opera-daily-ingest").resolve()
    script = skill_root / "scripts" / "process_daily.py"
    module_name = "_arr_runtime_process_daily"
    specification = importlib.util.spec_from_file_location(module_name, script)
    if specification is None or specification.loader is None:
        raise ValueError("ARR daily processor identity is unavailable")
    module = importlib.util.module_from_spec(specification)
    prior = sys.modules.get(module_name)
    sys.modules[module_name] = module
    try:
        specification.loader.exec_module(module)
        processor_version = str(module.PROCESSOR_VERSION)
        rule_set_sha256 = str(module.rule_set_sha256())
    finally:
        if prior is None:
            sys.modules.pop(module_name, None)
        else:
            sys.modules[module_name] = prior
    return ProcessorPolicy(
        processor_version=processor_version,
        rule_set_sha256=rule_set_sha256,
        skill_root=skill_root,
    )
