# aider-watch-client cli | 2026-04-20 @ Asia/Taipei
"""aider-watch subcommands: doctor, flush."""
from __future__ import annotations
import argparse, subprocess, sys
from aider_watch_client import config, buffer
from aider_watch_client.api_client import post_events


def cmd_doctor(_a) -> int:
    ok = True
    print("== aider-watch doctor ==")
    for k in ("AIDER_API_URL", "AIDER_WEBHOOK_SECRET"):
        v = config.get(k)
        mark = "ok" if v else "FAIL"
        print(f"  env {k:30s} {mark}")
        if not v:
            ok = False
    # API reachability
    try:
        import requests
        url = config.get("AIDER_API_URL", required=True)
        # use healthz if available; otherwise try the url itself (HEAD won't post events)
        health = url.replace("/aider/events", "/healthz")
        r = requests.get(health, timeout=3)
        mark = "ok" if r.status_code < 500 else "FAIL"
        print(f"  API reachable {mark} {r.status_code} ({health})")
        if r.status_code >= 500:
            ok = False
    except Exception as e:
        print(f"  API reachable FAIL {e}")
        ok = False
    # launchd
    res = subprocess.run(["launchctl", "list"], capture_output=True, text=True)
    mark = "ok" if "com.awoooi.aider-flush" in res.stdout else "FAIL"
    print(f"  launchd aider-flush     {mark}")
    return 0 if ok else 1


def cmd_flush(_a) -> int:
    n = buffer.flush(post_fn=post_events)
    print(f"flushed {n} events")
    return 0


def main() -> int:
    p = argparse.ArgumentParser(prog="aider-watch")
    sub = p.add_subparsers(dest="cmd", required=True)
    sub.add_parser("doctor").set_defaults(func=cmd_doctor)
    sub.add_parser("flush").set_defaults(func=cmd_flush)
    a = p.parse_args()
    return a.func(a)


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