#!/usr/bin/python3
# blob:summary=Record your voice from a microphone, with a noise suppressed copy, and play recordings back
# blob:args=[status|start|stop|toggle|play <original|cleaned> [file]|stop-playback|delete <file>|source <name>|clean on|off|folder]
# blob:group=audio

from __future__ import annotations

import json
import os
import signal
import subprocess
import sys
import time
import wave
from pathlib import Path
from typing import Any

RUNTIME_DIRECTORY = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "blob"
RUNTIME_FILE = RUNTIME_DIRECTORY / "voice-recorder.json"
STATE_DIRECTORY = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local" / "state"))) / "blob"
SETTINGS_FILE = STATE_DIRECTORY / "voice-recorder.json"
MAXIMUM_LISTED_RECORDINGS = 30
SAMPLE_RATE = 48000
CHANNELS = 1
CLEAN_SOURCE_NAMES = (
  ("hushmic", "DPDFNet"),
  ("dpdfnet", "DPDFNet"),
  ("blob_noise_suppression", "RNNoise"),
)


def run(command: list[str]) -> str:
  try:
    result = subprocess.run(command, capture_output=True, text=True, timeout=5)
  except (OSError, subprocess.TimeoutExpired):
    return ""
  return result.stdout.strip() if result.returncode == 0 else ""


def read_json(path: Path) -> dict[str, Any]:
  try:
    data = json.loads(path.read_text(encoding="utf-8"))
    return data if isinstance(data, dict) else {}
  except (OSError, ValueError):
    return {}


def write_json(path: Path, data: dict[str, Any]) -> None:
  path.parent.mkdir(parents=True, exist_ok=True)
  temporary = path.with_suffix(".tmp")
  temporary.write_text(json.dumps(data) + "\n", encoding="utf-8")
  temporary.replace(path)


def recordings_directory() -> Path:
  music = run(["xdg-user-dir", "MUSIC"]) or str(Path.home() / "Music")
  directory = Path(music) / "Recordings"
  directory.mkdir(parents=True, exist_ok=True)
  return directory


def list_sources() -> list[dict[str, str]]:
  try:
    sources = json.loads(run(["pactl", "-f", "json", "list", "sources"]) or "[]")
  except ValueError:
    return []
  listed = []
  for source in sources:
    name = str(source.get("name", ""))
    if not name or name.endswith(".monitor"):
      continue
    listed.append({"name": name, "description": str(source.get("description") or name)})
  return listed


def clean_engine(name: str) -> str:
  lowered = name.lower()
  for fragment, engine in CLEAN_SOURCE_NAMES:
    if fragment in lowered:
      return engine
  return ""


def clean_source(sources: list[dict[str, str]]) -> dict[str, str] | None:
  for fragment, engine in CLEAN_SOURCE_NAMES:
    for source in sources:
      if fragment in source["name"].lower():
        return {"name": source["name"], "description": source["description"], "engine": engine}
  return None


def default_source() -> str:
  return run(["pactl", "get-default-source"])


def microphone(sources: list[dict[str, str]]) -> dict[str, str] | None:
  plain_sources = [source for source in sources if not clean_engine(source["name"])]
  if not plain_sources:
    return None
  wanted = [read_json(SETTINGS_FILE).get("source", ""), default_source(), read_json(SETTINGS_FILE).get("restoreSource", "")]
  for name in wanted:
    for source in plain_sources:
      if name and source["name"] == name:
        return source
  return plain_sources[0]


def process_alive(pid: int) -> bool:
  try:
    os.kill(pid, 0)
  except OSError:
    return False
  return True


def start_record(target: str, path: Path) -> int:
  process = subprocess.Popen(
    ["pw-record", "--target", target, "--rate", str(SAMPLE_RATE), "--channels", str(CHANNELS), str(path)],
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
    start_new_session=True,
  )
  return process.pid


def stop_pids(pids: list[int]) -> None:
  for pid in pids:
    try:
      os.kill(pid, signal.SIGINT)
    except OSError:
      pass
  deadline = time.time() + 3
  while time.time() < deadline and any(process_alive(pid) for pid in pids):
    time.sleep(0.05)
  for pid in pids:
    if process_alive(pid):
      try:
        os.kill(pid, signal.SIGKILL)
      except OSError:
        pass


def wav_seconds(path: str) -> float:
  try:
    with wave.open(path, "rb") as audio:
      return audio.getnframes() / float(audio.getframerate() or 1)
  except (OSError, wave.Error, EOFError):
    return 0.0


def runtime() -> dict[str, Any]:
  data = read_json(RUNTIME_FILE)
  pids = [pid for pid in data.get("pids", []) if isinstance(pid, int)]
  if data.get("recording") and not any(process_alive(pid) for pid in pids):
    data["recording"] = False
    write_json(RUNTIME_FILE, data)
  playback_pid = data.get("playbackPid")
  if isinstance(playback_pid, int) and not process_alive(playback_pid):
    data["playbackPid"] = None
    data["playing"] = ""
    data["playingFile"] = ""
  return data


def start() -> None:
  data = runtime()
  if data.get("recording"):
    return
  sources = list_sources()
  source = microphone(sources)
  if source is None:
    print("No microphone found", file=sys.stderr)
    sys.exit(1)
  cleaned = clean_source(sources)
  stamp = time.strftime("%Y-%m-%d_%H-%M-%S")
  directory = recordings_directory()
  original_path = directory / f"voice-{stamp}.wav"
  pids = [start_record(source["name"], original_path)]
  cleaned_path = ""
  if cleaned:
    cleaned_file = directory / f"voice-{stamp}-cleaned.wav"
    pids.append(start_record(cleaned["name"], cleaned_file))
    cleaned_path = str(cleaned_file)
  data.update({
    "recording": True,
    "pids": pids,
    "startedAt": int(time.time() * 1000),
    "file": str(original_path),
    "cleanedFile": cleaned_path,
    "source": source["description"],
  })
  write_json(RUNTIME_FILE, data)


def stop() -> None:
  data = runtime()
  if not data.get("recording"):
    return
  stop_pids([pid for pid in data.get("pids", []) if isinstance(pid, int)])
  data["recording"] = False
  data["pids"] = []
  data["stoppedAt"] = int(time.time() * 1000)
  data["latest"] = {"file": data.get("file", ""), "cleanedFile": data.get("cleanedFile", ""), "source": data.get("source", "")}
  write_json(RUNTIME_FILE, data)


def recording_entry(original: Path) -> dict[str, Any]:
  cleaned = original.with_name(original.stem + "-cleaned.wav")
  return {
    "file": str(original),
    "cleanedFile": str(cleaned) if cleaned.is_file() else "",
    "name": original.name,
    "seconds": wav_seconds(str(original)),
    "modified": int(original.stat().st_mtime * 1000),
  }


def original_recordings() -> list[Path]:
  return sorted(
    (path for path in recordings_directory().glob("voice-*.wav") if not path.name.endswith("-cleaned.wav")),
    key=lambda path: path.stat().st_mtime,
    reverse=True,
  )


def list_recordings() -> list[dict[str, Any]]:
  return [recording_entry(path) for path in original_recordings()[:MAXIMUM_LISTED_RECORDINGS]]


def recording_path(file: str) -> Path | None:
  path = Path(file).resolve()
  if path.parent != recordings_directory().resolve() or not path.name.startswith("voice-") or path.suffix != ".wav":
    return None
  return recordings_directory() / path.name if path.is_file() else None


def delete_recording(file: str) -> None:
  original = recording_path(file)
  if original is None or original.name.endswith("-cleaned.wav"):
    print("Not a recording in the recordings folder", file=sys.stderr)
    sys.exit(1)
  data = runtime()
  if data.get("playingFile") == str(original):
    stop_playback()
  cleaned = original.with_name(original.stem + "-cleaned.wav")
  original.unlink(missing_ok=True)
  cleaned.unlink(missing_ok=True)


def latest_recording(data: dict[str, Any]) -> dict[str, Any] | None:
  latest = data.get("latest")
  if not isinstance(latest, dict) or not Path(str(latest.get("file", ""))).is_file():
    candidates = original_recordings()
    if not candidates:
      return None
    cleaned = candidates[0].with_name(candidates[0].stem + "-cleaned.wav")
    latest = {"file": str(candidates[0]), "cleanedFile": str(cleaned) if cleaned.is_file() else "", "source": ""}
  latest = dict(latest)
  latest["seconds"] = wav_seconds(str(latest["file"]))
  latest["name"] = Path(str(latest["file"])).name
  if latest.get("cleanedFile") and not Path(str(latest["cleanedFile"])).is_file():
    latest["cleanedFile"] = ""
  return latest


def play(which: str, file: str) -> None:
  stop_playback()
  data = runtime()
  if file:
    original = recording_path(file)
    recording = recording_entry(original) if original else None
  else:
    recording = latest_recording(data)
  if recording is None:
    return
  path = str(recording["cleanedFile"] if which == "cleaned" else recording["file"])
  if not path:
    return
  process = subprocess.Popen(["pw-play", path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
  data["playbackPid"] = process.pid
  data["playing"] = which
  data["playingFile"] = str(recording["file"])
  write_json(RUNTIME_FILE, data)


def stop_playback() -> None:
  data = runtime()
  playback_pid = data.get("playbackPid")
  if isinstance(playback_pid, int):
    stop_pids([playback_pid])
  data["playbackPid"] = None
  data["playing"] = ""
  data["playingFile"] = ""
  write_json(RUNTIME_FILE, data)


def set_source(name: str) -> None:
  settings = read_json(SETTINGS_FILE)
  settings["source"] = name
  write_json(SETTINGS_FILE, settings)


def clean_capture_stream() -> str:
  try:
    outputs = json.loads(run(["pactl", "-f", "json", "list", "source-outputs"]) or "[]")
  except ValueError:
    return ""
  for output in outputs:
    properties = output.get("properties", {})
    if str(properties.get("node.name", "")).startswith("capture.blob_noise_suppression"):
      return str(output.get("index", ""))
  return ""


def set_clean(enabled: bool) -> None:
  sources = list_sources()
  cleaned = clean_source(sources)
  source = microphone(sources)
  if cleaned is None or source is None:
    return
  settings = read_json(SETTINGS_FILE)
  if enabled:
    settings["restoreSource"] = source["name"]
    write_json(SETTINGS_FILE, settings)
    stream = clean_capture_stream()
    if stream:
      run(["pactl", "move-source-output", stream, source["name"]])
    run(["pactl", "set-default-source", cleaned["name"]])
  else:
    run(["pactl", "set-default-source", settings.get("restoreSource") or source["name"]])


def status() -> dict[str, Any]:
  data = runtime()
  sources = list_sources()
  source = microphone(sources)
  cleaned = clean_source(sources)
  current_default = default_source()
  return {
    "recording": bool(data.get("recording")),
    "startedAt": data.get("startedAt", 0),
    "stoppedAt": data.get("stoppedAt", 0),
    "rate": SAMPLE_RATE,
    "channels": CHANNELS,
    "source": source,
    "sources": [entry for entry in sources if not clean_engine(entry["name"])],
    "clean": {
      "available": cleaned is not None,
      "name": cleaned["name"] if cleaned else "",
      "description": cleaned["description"] if cleaned else "",
      "engine": cleaned["engine"] if cleaned else "",
      "active": bool(cleaned and current_default == cleaned["name"]),
    },
    "latest": latest_recording(data),
    "playing": data.get("playing", ""),
    "playingFile": data.get("playingFile", ""),
    "recordings": list_recordings(),
    "folder": str(recordings_directory()),
  }


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "status"
  value = arguments[1] if len(arguments) > 1 else ""
  extra = arguments[2] if len(arguments) > 2 else ""
  if action == "status":
    print(json.dumps(status()))
  elif action == "start":
    start()
  elif action == "stop":
    stop()
  elif action == "toggle":
    stop() if runtime().get("recording") else start()
  elif action == "play" and value in ("original", "cleaned"):
    play(value, extra)
  elif action == "stop-playback":
    stop_playback()
  elif action == "delete" and value:
    delete_recording(value)
  elif action == "source" and value:
    set_source(value)
  elif action == "clean" and value in ("on", "off"):
    set_clean(value == "on")
  elif action == "folder":
    subprocess.Popen(["xdg-open", str(recordings_directory())], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
  else:
    print("Usage: blob-voice-recorder [status|start|stop|toggle|play <original|cleaned> [file]|stop-playback|delete <file>|source <name>|clean on|off|folder]", file=sys.stderr)
    return 1
  return 0


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