#!/usr/bin/python3
# blob:summary=Status and controls for Plex, Immich and qBittorrent, with keys kept in the GNOME keyring
# blob:args=[config|status <plex|immich|qbittorrent>|setup <service> <url> [username]|forget <service>|qbittorrent pause|resume|add|remove|toggle-alternative [value]]
# blob:group=network

from __future__ import annotations

import json
import os
import re
import sys
from pathlib import Path
from typing import Any

BLOB_PATH = Path(os.environ.get("BLOB_PATH", str(Path.home() / ".local" / "share" / "blob")))
sys.path.insert(0, str(BLOB_PATH / "default" / "homelab"))

import immich
import plex
import qbittorrent
from web import ServiceError, clear_secret, lookup_secret, store_secret

CONFIG_FILE = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "blob" / "homelab.json"
SERVICES = ("plex", "immich", "qbittorrent")
DEFAULT_URLS = {"plex": "http://192.168.1.214:32400", "immich": "http://192.168.1.214:2283", "qbittorrent": "https://torr.sirblob.co"}
SECRET_LABELS = {"plex": "Plex token", "immich": "Immich API key", "qbittorrent": "qBittorrent password"}
URL_PATTERN = re.compile(r"https?://[A-Za-z0-9.\-\[\]:]+(:\d+)?(/[A-Za-z0-9._~/\-]*)?")


def load_config() -> dict[str, Any]:
  try:
    saved = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
  except (OSError, ValueError):
    saved = {}
  config = {service: {"url": DEFAULT_URLS[service], "username": ""} for service in SERVICES}
  for service in SERVICES:
    if isinstance(saved.get(service), dict):
      config[service].update({key: str(value) for key, value in saved[service].items() if key in ("url", "username")})
  return config


def save_config(config: dict[str, Any]) -> None:
  CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
  CONFIG_FILE.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")


def describe_config() -> dict[str, Any]:
  config = load_config()
  return {
    service: {
      "url": config[service]["url"],
      "username": config[service]["username"],
      "hasSecret": lookup_secret(service) != "",
    }
    for service in SERVICES
  }


def service_status(service: str) -> dict[str, Any]:
  config = load_config()[service]
  url = config["url"].rstrip("/")
  secret = lookup_secret(service)
  try:
    if service == "plex":
      data = plex.status(url, secret)
    elif service == "immich":
      data = immich.status(url, secret)
    else:
      data = qbittorrent.status(qbittorrent.Client(url, config["username"], secret))
  except ServiceError as error:
    return {"ok": False, "error": str(error), "configured": bool(url) and (bool(secret) or service == "qbittorrent")}
  return dict(data, ok=True, error="", configured=True)


def setup(service: str, url: str, username: str) -> int:
  if not URL_PATTERN.fullmatch(url):
    print("Use an address like http://192.168.1.214:32400", file=sys.stderr)
    return 2
  config = load_config()
  config[service] = {"url": url.rstrip("/"), "username": username}
  save_config(config)
  secret = sys.stdin.readline().strip() if not sys.stdin.isatty() else ""
  if secret and not store_secret(service, f"Blob {SECRET_LABELS[service]}", secret):
    print("Could not save to the keyring. Is it unlocked?", file=sys.stderr)
    return 1
  if service == "qbittorrent":
    qbittorrent.SESSION_FILE.unlink(missing_ok=True)
  return 0


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "config"
  service = arguments[1] if len(arguments) > 1 else ""
  if action == "config":
    print(json.dumps(describe_config()))
    return 0
  if action == "status" and service in SERVICES:
    print(json.dumps(service_status(service)))
    return 0
  if action == "setup" and service in SERVICES and len(arguments) > 2:
    return setup(service, arguments[2], arguments[3] if len(arguments) > 3 else "")
  if action == "forget" and service in SERVICES:
    clear_secret(service)
    if service == "qbittorrent":
      qbittorrent.SESSION_FILE.unlink(missing_ok=True)
    return 0
  if action == "qbittorrent" and service:
    config = load_config()["qbittorrent"]
    client = qbittorrent.Client(config["url"].rstrip("/"), config["username"], lookup_secret("qbittorrent"))
    try:
      qbittorrent.action(client, service, arguments[2] if len(arguments) > 2 else "")
    except ServiceError as error:
      print(str(error), file=sys.stderr)
      return 1
    return 0
  print("blob-homelab does not understand: " + " ".join(arguments), file=sys.stderr)
  return 2


if __name__ == "__main__":
  sys.exit(main(sys.argv[1:]))
