#!/usr/bin/env python3
"""atxpi CLI: управление питанием и консолью сервера.

Примеры:
  atxpi status
  atxpi on | off | reset | cycle
  atxpi console --cmd "uptime" --read      # скриптовый обмен
  atxpi console --read                      # просто прочитать буфер
"""
import argparse
import sys
import os

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

from atxpi.core import power as power_mod
from atxpi.core import console as console_mod


def main() -> int:
    ap = argparse.ArgumentParser(prog="atxpi", description=__doc__)
    sub = ap.add_subparsers(dest="action", required=True)

    sub.add_parser("status", help="текущее состояние питания")
    sub.add_parser("on", help="нажать кнопку питания (вкл/выкл)")
    sub.add_parser("off", help="принудительное выключение (длинное нажатие)")
    sub.add_parser("reset", help="аппаратный сброс")
    sub.add_parser("cycle", help="жёсткий перезапуск (выкл, пауза, вкл)")

    con = sub.add_parser("console", help="работа с RS232-консолью")
    con.add_argument("--cmd", help="отправить строку в консоль")
    con.add_argument("--read", action="store_true", help="прочитать и вывести буфер")

    args = ap.parse_args()

    try:
        if args.action == "status":
            print(_fmt(power_mod.status()))
        elif args.action == "on":
            print(_fmt(power_mod.press_power()))
        elif args.action == "off":
            print(_fmt(power_mod.force_off()))
        elif args.action == "reset":
            print(_fmt(power_mod.press_reset()))
        elif args.action == "cycle":
            print(_fmt(power_mod.cycle()))
        elif args.action == "console":
            if args.cmd:
                print(_fmt(console_mod.send(args.cmd)))
            if args.read or args.cmd:
                print(_fmt(console_mod.read_bytes()))
        return 0
    except Exception as e:
        print(f"atxpi: ошибка: {e}", file=sys.stderr)
        return 1


def _fmt(d: dict) -> str:
    return "  ".join(f"{k}={v}" for k, v in d.items())


if __name__ == "__main__":
    sys.exit(main())
