#!/usr/bin/env python3
import subprocess, time, os, sys, re

MM = "org.freedesktop.ModemManager1"
MODEM = "/org/freedesktop/ModemManager1/Modem/0"

def ox(iface, obj, method, *a):
    p = subprocess.run(["gdbus", "call", "--system", "-d", MM, "-o", obj,
                        "-m", "org.freedesktop.DBus.Properties.GetAll", iface],
                       capture_output=True, text=True)
    return p.stdout or p.stderr

def managed():
    p = subprocess.run(["gdbus", "call", "--system", "-d", MM, "-o", "/",
                        "-m", "org.freedesktop.DBus.ObjectManager.GetManagedObjects"],
                       capture_output=True, text=True)
    return p.stdout or ""

def calls():
    out = managed()
    paths = sorted(set(re.findall(r"/org/freedesktop/ModemManager1/Call/[0-9]+", out)))
    res = []
    for path in paths:
        s = ox("org.freedesktop.ModemManager1.Call", path, "GetAll")
        res.append(parse(path, s))
    return res

def parse(path, s):
    def gint(name):
        m = re.search(r"'%s':\s*<(?:uint32 )?(\d+)>" % name, s)
        return int(m.group(1)) if m else -1
    def gstr(name):
        m = re.search(r"'%s':\s*<'([^']*)'" % name, s)
        return m.group(1) if m else ""
    st = {0:"unknown",1:"dialing",2:"ringing-out",3:"ringing-in",
          4:"active",5:"held",6:"waiting",7:"terminated"}.get(gint("State"), "?")
    direc = "incoming" if gint("Direction") == 1 else "outgoing"
    return {"path": path, "num": gstr("Number"), "dir": direc,
            "state": st, "state_reason": gint("StateReason")}

def mmcli_call(path, action):
    r = subprocess.run(["mmcli", "-o", path, action], capture_output=True, text=True)
    return r.returncode

def fmt(c):
    dur = ""
    if c["state"] == "active":
        dur = " active"
    return "%-4s %-8s %-11s %s%s" % (c["path"].split("/")[-1], c["dir"], c["state"], c["num"], dur)

def do_list():
    cs = calls()
    if not cs:
        print("no calls")
        return
    for c in cs:
        print(fmt(c))

def do_answer(pid=None):
    cs = calls()
    if not cs:
        print("no calls"); return 1
    c = next((x for x in cs if x["state"] == "ringing-in" and (pid is None or c_ok(x, pid))), None)
    if not c:
        print("no ringing call"); return 1
    print("accept", c["num"])
    return mmcli_call(c["path"], "--accept")

def do_hangup(pid=None):
    cs = calls()
    if not cs:
        print("no calls"); return 1
    c = next((x for x in cs if c_ok(x, pid)), None)
    if not c:
        print("no call to end"); return 1
    print("hangup", c["num"])
    return mmcli_call(c["path"], "--hangup")

def c_ok(c, pid):
    return pid is None or c["path"].split("/")[-1] == str(pid)

def do_watch():
    started = {}
    last = {}
    while True:
        os.system("clear")
        cs = calls()
        now = time.time()
        if not cs:
            print("== no active calls ==")
        for c in cs:
            if c["state"] == "active":
                started.setdefault(c["path"], now)
                dur = int(now - started[c["path"]])
                print("== %s  %s  %s %02dm%02ds ==" % (c["dir"], c["num"], c["state"], dur // 60, dur % 60))
            else:
                if c["path"] in started and c["state"] == "terminated":
                    dur = int(now - started[c["path"]])
                    print("== %s  ended after %02dm%02ds ==" % (c["num"], dur // 60, dur % 60))
                    del started[c["path"]]
                else:
                    print(fmt(c))
        time.sleep(2)

USAGE = """call <cmd>
  list    show calls
  answer  accept ringing call (optional: answer <id>)
  hangup  end call (optional: hangup <id>)
  watch   live caller UI with call duration"""

def main():
    if len(sys.argv) < 2:
        print(USAGE); return 1
    cmd = sys.argv[1]
    pid = sys.argv[2] if len(sys.argv) > 2 else None
    if cmd == "list": return do_list()
    if cmd == "answer": return do_answer(pid)
    if cmd == "hangup": return do_hangup(pid)
    if cmd == "watch": return do_watch()
    print(USAGE); return 1

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