#!/usr/bin/env python3
"""Diagnostic (phase settings): print the live upgrade-base resolution for a recipe, using the EXACT
deployed `resolve_upgrade_base` reading the live server settings + canonical registry + recipe tags.

A lightweight, faithful, reproducible probe of the resolver decision (no deploy/test/teardown) — the
M2 evidence vehicle. Run from the repo root with the harness env:

    HOME=/root cc-ci-run scripts/show-upgrade-base.py <recipe> [<recipe> ...]

It prints, per recipe: the live SKIP_CANONICALS_FOR_UPGRADE value (+ source path), the canonical
registry version (or none), the head compose version, the newest release tag strictly older than head,
and the resolved BasePlan(kind, version, ref, reason). Flip the flag by dropping a scratch
/etc/cc-ci/settings.toml (or $CCCI_SETTINGS) and re-run.
"""

from __future__ import annotations

import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "runner"))

import run_recipe_ci  # noqa: E402
import warm_reconcile as wr  # noqa: E402
from harness import abra, canonical, lifecycle  # noqa: E402
from harness import meta as meta_mod  # noqa: E402
from harness import settings as settings_mod  # noqa: E402

ALL = {"install", "upgrade", "backup", "restore", "custom"}


def show(recipe: str) -> None:
    s = settings_mod.get()
    rec = canonical.read_registry(recipe)
    canon = rec.get("version") if rec else None
    head_version = abra.head_compose_version(recipe)
    head_ref = lifecycle.recipe_head_commit(recipe)
    older = wr.newest_older_version(wr.recipe_tags(recipe), head_version)
    meta = meta_mod.load(recipe)
    plan = run_recipe_ci.resolve_upgrade_base(
        ALL, meta, recipe, head_ref=head_ref, head_version=head_version
    )
    print(f"recipe={recipe}")
    print(
        f"  SKIP_CANONICALS_FOR_UPGRADE={s.skip_canonicals_for_upgrade} (from {settings_mod._resolve_path()})"
    )
    print(f"  canonical={canon}  head_version={head_version}  newest_release_tag<head={older}")
    print(
        f"  -> BasePlan(kind={plan.kind!r}, version={plan.version!r}, ref={(plan.ref or '')[:12]!r}, reason={plan.reason!r})"
    )


if __name__ == "__main__":
    for r in sys.argv[1:] or ["keycloak"]:
        show(r)
