import subprocess, os, glob, json, time

logs = sorted(glob.glob(os.path.expanduser("~/*.log")), key=os.path.getmtime, reverse=True)
if not logs:
    print(json.dumps({"phase":"idle","detail":"no logs","process":"","pass":0,"fail":0,"log":"","total_elapsed_s":0,"proc_elapsed_s":0,"completed_phases":0}))
    raise SystemExit

log = logs[0]
logname = os.path.basename(log)
# Use birth time (creation time) — getctime returns inode change time on Linux
try:
    log_start = float(subprocess.run(["stat", "--format=%W", log], capture_output=True, text=True).stdout.strip())
except:
    log_start = os.path.getctime(log)
with open(log) as f:
    content = f.read()
lines = content.strip().split("\n")
last = lines[-1][:120] if lines else ""

p = subprocess.run(["ps", "-eo", "pid,etimes,comm,args", "--no-headers"], capture_output=True, text=True)
procs = []
for l in p.stdout.strip().split("\n"):
    parts = l.split(None, 3)
    if len(parts) < 4:
        continue
    pid, etimes, comm, args = parts
    cmd = os.path.basename(comm)
    if cmd in ("build-index", "geocoder-diff", "geocoder-patch", "pyosmium-up-to-date", "python3"):
        if cmd == "python3" and "pyosmium" not in args and "remote_status" not in args:
            continue
        if cmd == "python3":
            cmd = "pyosmium"
        procs.append({"name": cmd, "elapsed": int(etimes)})

proc = procs[0] if procs else None
proc_name = proc["name"] if proc else ""
proc_elapsed = proc["elapsed"] if proc else 0
total_elapsed = int(time.time() - log_start)

real_count = sum(1 for l in lines if l.startswith("real\t") or l.startswith("real "))
passes = content.count("PASS")
# Use PASS count as completed_phases if no real lines (time output goes to stderr)
completed = real_count if real_count > 0 else passes
fails = content.count(": FAIL")
is_done = "=== DONE ===" in content

phase = "done" if is_done else ("running" if proc_name else "idle")

# Average duration of completed phases (excluding current in-progress one)
avg_phase_s = int((total_elapsed - proc_elapsed) / completed) if completed > 0 else 0

# Try to find total expected phases from log (e.g. "=== Build 2/5 ===")
import re
total_phases = 0
for l in reversed(lines):
    m = re.search(r'=== .+ (\d+)/(\d+) ===', l)
    if m:
        total_phases = int(m.group(2))
        break

print(json.dumps({
    "phase": phase,
    "process": proc_name,
    "detail": last,
    "pass": passes,
    "fail": fails,
    "log": logname,
    "total_elapsed_s": total_elapsed,
    "proc_elapsed_s": proc_elapsed,
    "completed_phases": completed,
    "avg_phase_s": avg_phase_s,
    "total_phases": total_phases,
}))
