#!/usr/bin/env python3
"""bridge — The Bridge driver (ParVagues dashboard + perf control).

    python3 bridge.py serve [--host --port]   # run the dashboard (default 127.0.0.1:8773)
    python3 bridge.py status                   # print a perf/thermal snapshot
    python3 bridge.py perf [cool|standard|extreme|normal]   # read or switch mode

Runs under system python3 (stdlib only). See README to install the systemd
--user service for always-on autostart.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import perf as P  # noqa: E402


def cmd_status(a):
    print(json.dumps(P.snapshot(), indent=2))


def cmd_perf(a):
    if not a.mode:
        s = P.snapshot()
        print(f"mode={s['mode']}  pkg={s['package_c']}°C ({s['temp_state']})  "
              f"freq={s['freq_max_mhz']}MHz  throttle+{s['throttle_delta']}")
        return
    ok, msg = P.set_mode(a.mode)
    print(("✓ " if ok else "✗ ") + msg)
    raise SystemExit(0 if ok else 1)


def cmd_serve(a):
    # Keep the chosen perf regime asserted across AC/battery flips & resume
    # (the platform silently resets pstate caps on those events).
    import threading
    threading.Thread(target=P.run_watcher, daemon=True,
                     name="perf-watcher").start()
    import server
    server.run(host=a.host, port=a.port)


def main(argv=None):
    p = argparse.ArgumentParser(prog="bridge", description=__doc__,
                                formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = p.add_subparsers(dest="cmd", required=True)
    sp = sub.add_parser("serve")
    sp.add_argument("--host", default="127.0.0.1")
    sp.add_argument("--port", type=int, default=8773)
    sp.set_defaults(fn=cmd_serve)
    sub.add_parser("status").set_defaults(fn=cmd_status)
    sp = sub.add_parser("perf"); sp.add_argument("mode", nargs="?"); sp.set_defaults(fn=cmd_perf)
    a = p.parse_args(argv)
    a.fn(a)


if __name__ == "__main__":
    main()
