#!/usr/bin/env python3
"""Victory Live command. `serve` is the systemd entry; `status --json` is for WUV OS."""
import json
import os
import sys

LIB = "/usr/lib/victoryclaw"
if os.path.isdir(os.path.join(os.path.dirname(__file__), "..", "lib", "victoryclaw")):
    LIB = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "lib", "victoryclaw"))
sys.path.insert(0, LIB)
os.environ.setdefault("PYTHONDONTWRITEBYTECODE", "1")
os.environ.setdefault("VICTORY_PROFILE", "live")


def load(name):
    import importlib.util
    path = os.path.join(LIB, name)
    spec = importlib.util.spec_from_file_location(name.replace("-", "_").replace(".py", ""), path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def main(argv):
    command = argv[1] if len(argv) > 1 else "status"
    if command == "serve":
        voice = load("victory-live-voice.py")
        return voice.main()
    if command == "status" and "--json" in argv:
        status = load("victory-live-status.py")
        document = status.read_status()
        if document is None:
            print(json.dumps({"error": "victory_live_not_installed"}))
            return 1
        print(json.dumps(document))
        return 0
    print("usage: victory-live serve | victory-live status --json", file=sys.stderr)
    return 2


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
