"""Layer 2 — Multiple fields + env override + save/load round-trip.

Shows a realistic small Settings class: a handful of typed fields,
env-var override, atomic save to disk, and a clean reload from disk
that produces an equal object.
"""

from __future__ import annotations

import os
import tempfile
from pathlib import Path

from mgf.common.config import (
    BaseAppSettings,
    load_settings,
    save_settings,
    settings_config,
)


class Settings(BaseAppSettings):
    model_config = settings_config(env_prefix="MYAPP_")

    backend_uri: str = "qemu:///system"
    ssh_timeout_seconds: int = 30
    log_level: str = "INFO"


def main() -> None:
    # Isolate disk side-effects so the example doesn't pollute $HOME.
    with tempfile.TemporaryDirectory() as tmp:
        config_path = Path(tmp) / "config.yaml"

        # ── Construct from defaults ──────────────────────────
        s1 = Settings()
        print(f"defaults: backend_uri={s1.backend_uri!r}, timeout={s1.ssh_timeout_seconds}")

        # ── Env override (MYAPP_LOG_LEVEL=DEBUG) ─────────────
        os.environ["MYAPP_LOG_LEVEL"] = "DEBUG"
        try:
            s2 = Settings()
            print(f"env-override: log_level={s2.log_level!r}")
        finally:
            # Always clean up env mutations — rule TS-03 (test
            # isolation) generalises to any code that touches
            # process-global state.
            del os.environ["MYAPP_LOG_LEVEL"]

        # ── Save (atomic write, mode 0o600 — rule CF-04) ─────
        save_settings(s1, config_path)
        print(f"wrote {config_path}: {oct(config_path.stat().st_mode)[-3:]} (mode)")

        # ── Reload from disk; should equal the original ──────
        s3 = load_settings(Settings, path=config_path)
        assert s3 == s1, "round-trip failed"
        print(f"reloaded: backend_uri={s3.backend_uri!r}, version={s3.version}")


if __name__ == "__main__":
    main()
