#!/usr/bin/env bash

# The idle generator's fallbacks must equal the schema's defaults.
#
# The Power page shows the schema default for an unwritten key; panama-idle
# generates from its own fallback for the same key. When the two disagreed
# (schema said suspend on battery at 20 minutes, the generator fell back to
# the AC value, never), a fresh laptop displayed one behavior and shipped
# another. The UI and the generator read the same file; this pins them to the
# same defaults too.

set -uo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"

python3 - "$repo_dir" <<'PY'
import re, sys, pathlib

repo = pathlib.Path(sys.argv[1])
schema = (repo / "config/dot/quickshell/config/PreferenceSchema.qml").read_text()
idle = (repo / "config/dot/quickshell/scripts/panama-idle").read_text()

def schema_default(key):
    m = re.search(r'key: "' + key + r'".*?def: ([-\d.]+|true|false)', schema, re.S)
    return m.group(1) if m else None

failures = []
# Every read_setting with a literal fallback, including the nested clamp_int
# default that guards a malformed value.
for key, fallback in re.findall(r'read_setting\s+"?([A-Za-z]+)"?\s+(?:\\\n\s*)?"?([\w.]+)"?', idle):
    expected = schema_default(key)
    if expected is None:
        failures.append(f"{key}: generator reads a key the schema does not declare")
    elif fallback != expected:
        failures.append(f"{key}: generator falls back to {fallback}, schema default is {expected}")

if failures:
    print(f"idle defaults contract: {len(failures)} finding(s)")
    for failure in failures:
        print(f"  - {failure}")
    sys.exit(1)
print("idle defaults contract: ok (generator fallbacks match the schema)")
PY
