import argparse
import json
import re
import subprocess
from collections.abc import Mapping
from copy import deepcopy
from functools import lru_cache
from pathlib import Path
from typing import Any, cast

import yaml

from scripts import ci_branch_lanes, ci_reuse, ci_runner_trust, ci_wiring

GATE = ci_wiring.GATE
WORKFLOWS = ".github/workflows"
SHALLOW_PREFLIGHT_CHECKOUT = {
    "fetch-depth": 1,
    "sparse-checkout": (
        "/.github/workflows/\n/scripts/__init__.py\n/scripts/gh_config.py\n/scripts/ci_branch_lanes.py\n"
    ),
    "sparse-checkout-cone-mode": False,
}
FULL_PREFLIGHT_CHECKOUT = {"fetch-depth": 0}
PREFLIGHT_FETCH = 'git fetch --no-tags origin "$GITHUB_SHA"'
SHALLOW_PREFLIGHT_FETCH = 'git fetch --no-tags --depth 1 origin "$GITHUB_SHA"'
EQUIVALENCE = ("equivalence.yml", "ledger-equivalence")
MUTATION_STAGES = ("mutation-refine", "mutation-probe", "mutation-replan", "mutation-shard")
EQUIVALENCE_WORDS = ("GRADER", "GITHUB_ENV", "GITHUB_PATH", "equivalence.sh")
EQUIVALENCE_TUNABLE = ("steps", "timeout-minutes")
EQUIVALENCE_DEV_PARENT = {
    "name": "Select the dev parent of the tested merge",
    "id": "comparison-base",
    "run": 'echo "sha=$(git -C head rev-parse HEAD^1)" >> "$GITHUB_OUTPUT"',
}
EQUIVALENCE_DEV_PARENT_REF = "${{ steps.comparison-base.outputs.sha }}"
EQUIVALENCE_SCM_PIN = {"SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AGENTIHOOKS": "0.dev${{ github.run_number }}"}
PREFLIGHT_PATHS = [".github/workflows/**"]
EQUIVALENCE_PATHS = ["scripts/swarm_ledger/**", "tests/swarm_ledger/**", ".github/workflows/equivalence.yml"]
UNUSED_SELECT_OUTPUTS = ("files_1", "files_2", "files_3")
SONAR_SELECT_OUTPUT = {"sonar": "${{ steps.select.outputs.sonar }}"}
LEDGER_SELECT_OUTPUT = {"ledger": "${{ steps.select.outputs.ledger }}"}
FROZEN = "tests/registry/FROZEN_GATES.json"
LAB_VERDICT_JOB = "lab-verdict"
LAB_CLAUSE_PREFIX = f"fromJSON(needs.{LAB_VERDICT_JOB}.outputs.authoritative || '{{}}')"
LAB_UPSTREAM = frozenset({"reuse", LAB_VERDICT_JOB})
DOWNLOAD_ARTIFACT = "actions/download-artifact@"
SUMMARY_DOWNLOADS = ("actions/download-artifact@v4", "actions/download-artifact@v8.0.2")
SUMMARY_REPORTS = ("Download this run's test reports", "{durations,flakes}-3.*")


def _gates(workflows: dict[str, dict]) -> list[tuple[str, str, dict]]:
    return [
        (file, job_id, job)
        for file, workflow in workflows.items()
        for job_id, job in (workflow.get("jobs") or {}).items()
        if job.get("name") == GATE
    ]


def _protected_config(base: Mapping[str, Any], head: Mapping[str, Any]) -> dict:
    return {
        section: {key: entry for key, entry in base.get(section, {}).items() if key in head.get(section, {})}
        for section in ("not_gates", "outside_gate")
    }


def _summary_download(steps: list[dict[str, Any]], uses: str) -> list[dict[str, Any]]:
    """Return the reviewed summary steps with every artifact download step pinned to ``uses``."""
    return [{**step, "uses": uses} if str(step.get("uses")).startswith(DOWNLOAD_ARTIFACT) else step for step in steps]


def _one_download(steps: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Return the reviewed summary steps with one step, in the first download's place, downloading every report."""
    name, pattern = SUMMARY_REPORTS
    joined: list[dict[str, Any]] = []
    for step in steps:
        if not str(step.get("uses")).startswith(DOWNLOAD_ARTIFACT):
            joined.append(step)
        elif not any(str(kept.get("uses")).startswith(DOWNLOAD_ARTIFACT) for kept in joined):
            joined.append({**step, "name": name, "with": {**step["with"], "pattern": pattern}})
    return joined


def runners(policy: object = None) -> list[str]:
    anton = (
        [ci_runner_trust.selector(policy, "anton-oss-light", trusted_reruns=reruns) for reruns in (False, True)]
        if isinstance(policy, dict)
        else []
    )
    return ["ubuntu-latest", *anton]


def _pinned_tool_form(value: Any) -> Any:
    if isinstance(value, dict):
        return {key: _pinned_tool_form(item) for key, item in value.items()}
    if isinstance(value, list):
        return [_pinned_tool_form(item) for item in value]
    if not isinstance(value, str):
        return value
    for requirement in ('"pyyaml>=6.0"', "'pyyaml>=6.0'"):
        value = value.replace(
            f"pip install {requirement}",
            "pip install --constraint .github/ci-tools/parser.lock PyYAML==6.0.3",
        )
    if value == SHALLOW_PREFLIGHT_CHECKOUT["sparse-checkout"]:
        return value + "/.github/ci-tools/\n"
    return value


def _floating_tool_form(value: Any) -> Any:
    """Write the pinned parser install back in the single quoted form the provenance template held before its pin."""
    if isinstance(value, dict):
        return {key: _floating_tool_form(item) for key, item in cast(dict[Any, Any], value).items()}
    if isinstance(value, list):
        return [_floating_tool_form(item) for item in cast(list[Any], value)]
    if not isinstance(value, str):
        return value
    return value.replace(
        "pip install --constraint .github/ci-tools/parser.lock PyYAML==6.0.3", "pip install 'pyyaml>=6.0'"
    )


def reuse_jobs(policy: object = None) -> list[dict]:
    jobs = []
    for factory in (ci_reuse.reuse_job, ci_reuse.paged_reuse_job, ci_reuse.retried_reuse_job):
        for runner in runners(policy):
            job = factory()
            if runner != job["runs-on"]:
                job["runs-on"] = runner
                [install] = [step for step in job["steps"] if step.get("name") == "Install metadata dependencies"]
                install["env"] = {"PYTHONNOUSERSITE": "1"}
            jobs.append(job)
            jobs.append({**job, "if": "github.event_name != 'merge_group' && github.event_name != 'pull_request'"})
    return [*jobs, *(_pinned_tool_form(job) for job in jobs)]


@lru_cache(maxsize=None)
def _accepted_steps_renderings(type_gate: bool, postgres: bool, docs: bool) -> list[list[dict[str, Any]]]:
    """Every rendering of the gate-required job's steps the protected branch still accepts, for one (type_gate, postgres, docs) combination."""
    requirements = (ci_reuse.postgres_required,) if postgres else (list, ci_reuse.postgres_required)
    return [
        typing(
            sonar(
                diagnostic(
                    forward(
                        finish(
                            rerun(
                                shape(
                                    required(
                                        lab(
                                            ledger(
                                                ci_reuse.gate_steps(
                                                    **form,
                                                    summary=summary,
                                                    docs=docs,
                                                    watcher_loss=watcher_loss,
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                        )
                    )
                )
            )
        )
        for typing in ((ci_reuse.typing_required,) if type_gate else (list,))
        for sonar in (list, ci_reuse.test_only_sonar)
        for diagnostic, forward in (
            (list, list),
            (ci_reuse.selection_diagnostic, list),
            (ci_reuse.selection_diagnostic, ci_reuse.forwarded_stats),
            (ci_reuse.selection_diagnostic, ci_reuse.collected_stats),
        )
        for form in (
            {},
            {"selected": True},
            {"queue_tier": True},
            {"queue_tier": True, "promotion": True},
            {"queue_tier": True, "consolidated": True},
            {"queue_tier": True, "promotion": True, "consolidated": True},
        )
        for summary in (False, True)
        for watcher_loss in (False, True)
        for required in requirements
        for lab in (list[dict[str, Any]], ci_reuse.lab_verdict)
        for ledger in (list[dict[str, Any]], ci_reuse.ledger_required)
        for rerun in (list, ci_reuse.lost_rerun)
        for shape in (list, ci_reuse.inline_mutation)
        for finish in (list, ci_reuse.pipefail_summary)
    ]


def _aggregator_problems(
    base: tuple[str, str, dict], head: tuple[str, str, dict], policy: object = None, retired: frozenset = frozenset()
) -> list[str]:
    (base_file, base_id, base_job), (head_file, head_id, head_job) = base, head
    if (base_file, base_id) != (head_file, head_id):
        return [f"The head moves {GATE} from {base_file}/{base_id} to {head_file}/{head_id}."]
    problems = [
        f"The head's {GATE} drops the base need {need}."
        for need in sorted(ci_wiring.needs_of(base_job) - ci_wiring.needs_of(head_job) - retired)
    ]
    fields = sorted((set(base_job) | set(head_job)) - {"needs"})
    postgres = any(ci_reuse.POSTGRES_REQUIRED[1] in str(step.get("run")) for step in base_job.get("steps") or [])
    return problems + [
        f"The head's {GATE} changes its {field}; the protected branch grades with its own."
        for field in fields
        if (
            base_job.get(field) != head_job.get(field)
            or field == "steps"
            and base_id == "gate-required"
            and {"docs", "type-gate"} & ci_wiring.needs_of(head_job)
        )
        and not (
            field == "steps"
            and base_id == "gate-required"
            and head_job.get("steps")
            in _accepted_steps_renderings(
                "type-gate" in ci_wiring.needs_of(head_job), postgres, "docs" in ci_wiring.needs_of(head_job)
            )
        )
        and not (field == "runs-on" and head_job.get(field) in runners(policy))
    ]


def _reuse_problems(base: dict, head: dict, policy: object = None) -> list[str]:
    previous = base.get("reuse")
    candidate = head.get("reuse")
    if candidate is None:
        return ["The head removes the protected reuse job."] if previous is not None else []
    if candidate != previous and candidate not in reuse_jobs(policy):
        return ["The head changes the protected reuse job; the protected branch grades with its own."]
    return []


def lab_clause(condition: str | None, gate: str) -> str:
    """Return the gate condition with the clause that skips the gate in Actions while the lab grades it."""
    clause = f"{LAB_CLAUSE_PREFIX}['{gate}'] != true"
    if condition is None:
        return f"${{{{ {clause} }}}}"
    if condition.startswith("${{") and condition.endswith("}}"):
        return f"{condition.removesuffix('}}').rstrip()} && {clause} }}}}"
    return f"{condition} && {clause}"


def _reads_needs_freely(condition: str) -> bool:
    """Return whether a condition reads the needs context, in any letter case, other than by a literal job name."""
    bare = re.sub(r"'(?:[^']|'')*'", "''", condition)
    return re.search(r"(?<![\w.-])needs\b(?!\s*(?:\.\s*\w|\[\s*''\s*\]))", bare, flags=re.IGNORECASE) is not None


def _lab_problems(base: dict[str, Any], head: dict[str, Any], gate: dict[str, Any]) -> list[str]:
    """Refuse a lab verdict job or a gate condition off its reviewed form.

    A gate whose base condition reads the lab verdict keeps that condition exactly. Any other gate reads the lab
    verdict, or the needs context by a computed key or as a whole, only through its base condition plus its exact lab
    clause.
    """
    problems: list[str] = []
    if head.get(LAB_VERDICT_JOB) != base.get(LAB_VERDICT_JOB):
        problems.append(
            "The head's lab verdict job differs from the reviewed rendering; the protected branch grades with its own."
        )

    def off_base(need: str) -> bool:
        condition: str | None = head[need].get("if")
        reviewed: str | None = base[need].get("if")
        if LAB_VERDICT_JOB in str(reviewed).lower():
            return condition != reviewed
        reads = LAB_VERDICT_JOB in str(condition).lower() or _reads_needs_freely(str(condition))
        return reads and condition not in (reviewed, lab_clause(reviewed, need))

    return problems + [
        f"The head's {need} condition differs from its base condition plus its exact lab clause; "
        "the protected branch grades with its own."
        for need in sorted(ci_wiring.needs_of(gate) - LAB_UPSTREAM)
        if need in base and need in head and off_base(need)
    ]


def _duration_problems(base: dict, head: dict) -> list[str]:
    if (
        head["jobs"].get("reuse", {}).get("if")
        != "github.event_name != 'merge_group' && github.event_name != 'pull_request'"
    ):
        return []
    previous = base["jobs"].get("durations", base["jobs"].get("select", {}))
    producer = head["jobs"].get("durations", head["jobs"].get("select", {}))
    prefix = ci_reuse.duration_provenance_steps()
    retried = ci_reuse.retried_duration_provenance_steps()
    problems = []
    if "durations" in base["jobs"] and "durations" not in head["jobs"]:
        selection = base["jobs"].get("select", {})
        if not selection:
            problems.append("The head moves durations provenance without existing selection admission.")
        previous = previous | {
            "outputs": previous.get("outputs", {}) | selection.get("outputs", {}),
            "timeout-minutes": selection.get("timeout-minutes"),
        }
    bounds = {"env": {"GIT_HTTP_LOW_SPEED_LIMIT": "1000", "GIT_HTTP_LOW_SPEED_TIME": "60"}}
    admitted = [variant for steps in (prefix, retried) for variant in (steps, [steps[0] | bounds, *steps[1:]])]
    admitted += [form(steps) for steps in admitted for form in (_pinned_tool_form, _floating_tool_form)]
    if producer.get("steps", [])[: len(prefix)] not in admitted:
        problems.append("The head skips reuse without protected durations provenance.")
    mutable = {"steps", "if", "runs-on"}
    selection_permissions = ({"contents": "read"}, {"contents": "read", "actions": "read"})
    if (
        "durations" not in head["jobs"]
        and previous.get("permissions") in selection_permissions
        and producer.get("permissions") in selection_permissions
    ):
        mutable.add("permissions")
    outputs = previous.get("outputs") or {}
    trimmed = {key: value for key, value in outputs.items() if key not in UNUSED_SELECT_OUTPUTS}
    problems += [
        f"The head changes the durations provenance context {field}."
        for field in sorted((set(previous) | set(producer)) - mutable)
        if previous.get(field) != producer.get(field)
        and not (
            field == "outputs"
            and producer is head["jobs"].get("select")
            and (
                set(UNUSED_SELECT_OUTPUTS).issubset(outputs)
                and producer.get(field) == trimmed
                or "sonar" not in outputs
                and producer.get(field) == outputs | SONAR_SELECT_OUTPUT
                or "ledger" not in outputs
                and producer.get(field) == outputs | LEDGER_SELECT_OUTPUT
            )
        )
    ]
    problems += [
        f"The head changes the global provenance context {field}."
        for field in ("env", "defaults")
        if base.get(field) != head.get(field)
    ]
    return problems


def _mutation_stage_entries(
    file: str, gate: dict[str, Any], jobs: dict[str, Any], head_config: Mapping[str, Any]
) -> dict[str, Any]:
    """Return the head's non gate entries for mutation stages whose results the required mutation job merges."""
    needs = ci_wiring.needs_of
    mutation: dict[str, Any] = jobs.get("mutation") or {}
    if "mutation" not in needs(gate):
        return {}
    declared: dict[str, Any] = head_config.get("not_gates", {})
    return {
        f"{file}/{stage}": declared[f"{file}/{stage}"]
        for stage in MUTATION_STAGES
        if f"{file}/{stage}" in declared and stage in needs(mutation)
    }


def _pinned_names(base_workflows: dict[str, dict[str, Any]], head_workflows: dict[str, dict[str, Any]]) -> list[str]:
    from scripts import ci_gate_queue

    return [
        f"The head changes or removes the reviewed name of {file}/{job_id}; the protected branch pins it."
        for file, workflow in base_workflows.items()
        for job_id, job in (workflow.get("jobs") or {}).items()
        if job.get("name") in (ci_gate_queue.GATE_NAME, ci_gate_queue.SUMMARY_NAME)
        and (((head_workflows.get(file) or {}).get("jobs") or {}).get(job_id) or {}).get("name") != job["name"]
    ]


def grade(
    base_workflows: dict[str, dict[str, Any]],
    base_config: ci_wiring.Wiring,
    head_workflows: dict[str, dict[str, Any]],
    head_config: ci_wiring.Wiring,
    policy: object = None,
) -> list[str]:
    from scripts import ci_gate_queue

    pinned = _pinned_names(base_workflows, head_workflows)
    try:
        base_workflows = ci_gate_queue.normalize(base_workflows)
        head_workflows = ci_gate_queue.normalize(head_workflows)
    except ValueError as error:
        return pinned + [str(error)]
    base_gates, head_gates = _gates(base_workflows), _gates(head_workflows)
    if len(base_gates) != 1:
        return [f"The base holds {len(base_gates)} jobs named {GATE}; nothing protected can grade."]
    if len(head_gates) != 1:
        return [f"The head holds {len(head_gates)} jobs named {GATE}; exactly one must be."]
    file = base_gates[0][0]
    head_jobs = (head_workflows.get(file) or {}).get("jobs") or {}
    retired = frozenset(
        job_id
        for job_id, job in base_workflows[file]["jobs"].items()
        if job.get("if") is False and job_id not in head_jobs
    )
    duration_problems = _duration_problems(base_workflows[file], head_workflows.get(file, {"jobs": {}}))
    if (
        "durations" in base_workflows[file]["jobs"]
        and "durations" not in head_jobs
        and head_jobs.get("reuse", {}).get("if")
        == "github.event_name != 'merge_group' && github.event_name != 'pull_request'"
        and not duration_problems
    ):
        retired = retired | {"durations"}
    problems = _aggregator_problems(base_gates[0], head_gates[0], policy, retired)
    problems += _reuse_problems(base_workflows[file]["jobs"], head_jobs, policy)
    problems += _lab_problems(
        base_workflows[file]["jobs"],
        cast("dict[str, Any]", head_jobs),  # pragma: no mutate
        cast("dict[str, Any]", head_gates[0][2]),  # pragma: no mutate
    )
    problems += duration_problems
    config = _protected_config(base_config, head_config)
    summary = head_jobs.get("test-summary")
    if summary is not None:
        canonical = [
            {
                "needs": ["unit", "unit-selected"],
                "if": "${{ always() }}",
                "runs-on": runner,
                "timeout-minutes": 5,
                "steps": finish(retry(join(_summary_download(ci_reuse.summary_steps(), uses)))),
            }
            for runner in runners(policy)
            for uses in SUMMARY_DOWNLOADS
            for join in (list, _one_download)
            for finish in (list, ci_reuse.pipefail_summary)
            for retry in (list, ci_reuse.retried_summary)
        ]
        if summary not in canonical:
            problems.append("The test summary must use the reviewed reporting job.")
        else:
            key = f"{file}/test-summary"
            if key in head_config.get("not_gates", {}):
                config["not_gates"].setdefault(key, head_config["not_gates"][key])
    for key, entry in _mutation_stage_entries(file, head_gates[0][2], head_jobs, head_config).items():
        config["not_gates"].setdefault(key, entry)
    return pinned + problems + ci_wiring.check(head_workflows, config)


def _git(root: Path, *args: str) -> str:
    return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True, text=True).stdout


def load(root: Path, rev: str) -> tuple[dict[str, dict], dict]:
    tracked = _git(root, "ls-tree", "-r", "-z", "--name-only", rev).split("\0")
    workflows = {
        Path(path).name: yaml.safe_load(_git(root, "show", f"{rev}:{path}")) or {}
        for path in tracked
        if Path(path).parent == Path(WORKFLOWS) and path.endswith((".yml", ".yaml"))
    }
    config = json.loads(_git(root, "show", f"{rev}:{ci_wiring.CONFIG}")) if ci_wiring.CONFIG in tracked else {}
    return workflows, config


def _preflight_problems(
    base_workflows: dict[str, dict[Any, Any]], head_workflows: dict[str, dict[Any, Any]]
) -> list[str]:
    baseline = base_workflows.get("branch-lanes.yml")
    if baseline is None:
        return []
    expanded = deepcopy(baseline)
    events = expanded[True] if True in expanded else expanded["on"]
    ignored = (events.get("push") or {}).get("branches-ignore", [])
    if "diffcheck/**" in ignored:
        ignored.remove("diffcheck/**")
    forms = [*_path_forms(baseline, "push", PREFLIGHT_PATHS), *_path_forms(expanded, "push", PREFLIGHT_PATHS)]
    admitted = [*forms, *(form for kept in forms for form in _checkout_forms(kept))]
    if head_workflows.get("branch-lanes.yml") in [*admitted, *(_pinned_tool_form(form) for form in admitted)]:
        return []
    return ["The head changes or removes the trusted branch lane preflight."]


def _path_forms(workflow: dict[Any, Any], event: str, paths: list[str]) -> list[dict[Any, Any]]:
    """Return the workflow as given, then with its event trigger unfiltered and filtered to the paths."""
    forms = [workflow]
    for kept in (None, paths):
        form = deepcopy(workflow)
        events: dict[str, Any] = form[True] if True in form else form["on"]
        if event in events:
            trigger: dict[str, Any] = dict(events[event] or {})
            trigger.pop("paths", None)
            events[event] = {**trigger, "paths": list(kept)} if kept else (trigger or None)
        forms.append(form)
    return forms


def _checkout_forms(preflight: dict) -> list[dict]:
    forms = []
    for checkout, fetch in (
        (SHALLOW_PREFLIGHT_CHECKOUT, SHALLOW_PREFLIGHT_FETCH),
        (FULL_PREFLIGHT_CHECKOUT, PREFLIGHT_FETCH),
    ):
        form = deepcopy(preflight)
        steps = ((form.get("jobs") or {}).get("grade") or {}).get("steps") or [{}]
        settings = steps[0].get("with", {})
        for key in SHALLOW_PREFLIGHT_CHECKOUT:
            settings.pop(key, None)
        settings.update(checkout)
        for step in steps:
            if step.get("run") in (PREFLIGHT_FETCH, SHALLOW_PREFLIGHT_FETCH):
                step["run"] = fetch
        forms.append(form)
    return forms


def _dev_parent_form(steps: list[dict]) -> list[dict]:
    form = deepcopy(steps)
    if EQUIVALENCE_DEV_PARENT in form:
        return form
    for index, step in list(enumerate(form)):
        settings = step.get("with") or {}
        if settings.get("path") == "base":
            settings["ref"] = EQUIVALENCE_DEV_PARENT_REF
        if settings.get("path") == "head":
            settings["fetch-depth"] = 2
            form.insert(index + 1, EQUIVALENCE_DEV_PARENT)
    return form


def _scm_pin_form(steps: list[dict[str, Any]], pin: dict[str, str]) -> list[dict[str, Any]]:
    form = deepcopy(steps)
    for step in form:
        if "pip install" in str(step.get("run")):
            kept = {key: value for key, value in step.get("env", {}).items() if key not in EQUIVALENCE_SCM_PIN}
            step["env"] = {**kept, **pin}
    return form


def _equivalence_problems(
    base_workflows: dict[str, dict[Any, Any]], head_workflows: dict[str, dict[Any, Any]]
) -> list[str]:
    file, job_id = EQUIVALENCE
    base, head = base_workflows.get(file) or {}, head_workflows.get(file) or {}
    base_job, head_job = ((workflow.get("jobs") or {}).get(job_id) or {} for workflow in (base, head))
    base_steps, head_steps = base_job.get("steps") or [], head_job.get("steps") or []
    graded = [index for index, step in enumerate(base_steps) if "$GRADER" in str(step.get("run"))]
    if not graded:
        return []
    end = graded[-1] + 1
    forms = [
        base_steps[:end],
        _dev_parent_form(base_steps[:end]),
        _scm_pin_form(base_steps[:end], EQUIVALENCE_SCM_PIN),
        _scm_pin_form(base_steps[:end], {}),
    ]
    accepted = next((form for form in forms if head_steps[: len(form)] == form), None)
    if (
        accepted is None
        or any(word in json.dumps(step) for step in head_steps[len(accepted) :] for word in EQUIVALENCE_WORDS)
        or {key: value for key, value in head.items() if key != "jobs"}
        not in [
            {key: value for key, value in form.items() if key != "jobs"}
            for form in _path_forms(base, "pull_request", EQUIVALENCE_PATHS)
        ]
        or {key: value for key, value in head_job.items() if key not in EQUIVALENCE_TUNABLE}
        != {key: value for key, value in base_job.items() if key not in EQUIVALENCE_TUNABLE}
    ):
        return ["The head changes the ledger equivalence grading; the protected branch grades with its own."]
    return []


def _filtered_equivalence(
    base_workflows: dict[str, dict[Any, Any]], head_workflows: dict[str, dict[Any, Any]]
) -> set[str]:
    """Name the equivalence workflow when the head only adds or drops its ledger path filter, so lanes keep trusting it."""
    file = EQUIVALENCE[0]
    base = base_workflows.get(file)
    if base is None or head_workflows.get(file) not in _path_forms(base, "pull_request", EQUIVALENCE_PATHS):
        return set()
    return {file}


def _blob(root: Path, rev: str, path: str) -> str | None:
    listing = _git(root, "ls-tree", rev, path).split()
    return listing[2] if listing[1:2] == ["blob"] else None


def _frozen_problems(root: Path, merge_base: str, base: str, head: str) -> list[str]:
    if _blob(root, base, FROZEN) is None:
        return []
    registry = json.loads(_git(root, "show", f"{base}:{FROZEN}"))

    def changed(path: str) -> bool:
        return _blob(root, head, path) not in {_blob(root, merge_base, path), _blob(root, base, path)}

    if changed(FROZEN):
        kept = json.loads(_git(root, "show", f"{head}:{FROZEN}")) if _blob(root, head, FROZEN) else {}
        return [
            f"The head drops the frozen gate file {path} from {FROZEN}; a frozen file stays frozen."
            for path in sorted(set(registry) - set(kept))
        ] + [
            f"The head changes {FROZEN} and the frozen gate file {path} together; "
            "land the registry by its own pull request first."
            for path in sorted(registry)
            if changed(path)
        ]
    return [
        f"The head changes the frozen gate file {path} to content {FROZEN} on the base does not accept; "
        "announce its blob there by its own pull request first."
        for path, accepted in sorted(registry.items())
        if changed(path) and _blob(root, head, path) not in accepted
    ]


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", default=".")
    parser.add_argument("--head", required=True)
    parser.add_argument("--base", default="HEAD")
    args = parser.parse_args(argv)
    root = Path(args.root)
    merge_base = _git(root, "merge-base", args.base, args.head).strip()
    base_workflows, branched_config = load(root, merge_base)
    tip_workflows, tip_config = load(root, args.base)
    base_config = {
        section: {**branched_config.get(section, {}), **tip_config.get(section, {})}
        for section in ("not_gates", "outside_gate")
    }
    head_workflows, head_config = load(root, args.head)
    actors = None
    if ci_runner_trust.ACTORS in _git(root, "ls-tree", "-r", "--name-only", args.base).splitlines():
        actors = json.loads(_git(root, "show", f"{args.base}:{ci_runner_trust.ACTORS}"))
        ci_runner_trust.validate_actors(actors)
    problems = grade(base_workflows, base_config, head_workflows, head_config, actors)
    preflight = _preflight_problems(tip_workflows, head_workflows)
    governed = {"branch-lanes.yml"} if "branch-lanes.yml" in tip_workflows and not preflight else set()
    governed |= _filtered_equivalence(base_workflows, head_workflows)
    problems += preflight
    problems += _equivalence_problems(tip_workflows, head_workflows)
    problems += _frozen_problems(root, merge_base, args.base, args.head)
    problems += [
        f"{file}: {problem}"
        for file, workflow in head_workflows.items()
        if file not in governed and workflow != base_workflows.get(file)
        for problem in ci_branch_lanes.problems(workflow, base_workflows.get(file))
    ]
    if actors is not None:
        problems += ci_runner_trust.check(head_workflows, actors)
    print(f"graded {args.head[:12]} against merge base {merge_base[:12]}: {len(problems)} protected gate problems")
    for problem in problems:
        print(f"::error::{problem}")
    return 1 if problems else 0


if __name__ == "__main__":
    raise SystemExit(main())
