#!/usr/bin/env python3
"""
Long-running poller for a conversation on the mrktplaats-cli.

Usage: python3 scripts/poll_nvidia_reply.py --conv CONV_ID --user USER_ID [--interval 900]

The script runs in a loop, calling `go run main.go messages --conv CONV_ID --limit 50`
in the repo directory, parses the JSON output and exits when it finds any message
whose `sender_id` is not the provided USER_ID (i.e. a seller reply).

When a reply is found the script writes a JSON file with the matching messages to
/home/joren/.local/share/opencode/tool-output/nvidia_reply_found.json and exits with
code 0. It logs progress to stdout/stderr so you can follow the `nohup` log file.
"""

import argparse
import json
import subprocess
import time
import os
from datetime import datetime


def now():
    return datetime.utcnow().isoformat() + "Z"


def fetch_messages(conv, workdir):
    # Run the mrktplaats-cli to fetch the conversation messages
    cmd = ["go", "run", "main.go", "messages", "--conv", conv, "--limit", "50"]
    proc = subprocess.run(cmd, cwd=workdir, capture_output=True, text=True)
    if proc.returncode != 0:
        raise RuntimeError(f"messages command failed: {proc.stderr.strip()}")
    return proc.stdout


def find_foreign_messages(json_text, user_id):
    data = json.loads(json_text)
    msgs = data.get("messages") or []
    foreign = [m for m in msgs if int(m.get("sender_id", 0)) != int(user_id)]
    return foreign


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--conv", required=True, help="Conversation id to poll")
    parser.add_argument("--user", required=True, help="Our user id (numeric)")
    parser.add_argument(
        "--interval",
        type=int,
        default=900,
        help="Poll interval in seconds (default 900 = 15m)",
    )
    parser.add_argument(
        "--workdir",
        default="/home/joren/dev/marktplaatsApi/mrktplaats-cli",
        help="Path to mrktplaats-cli repo",
    )
    args = parser.parse_args()

    out_dir = os.path.expanduser("/home/joren/.local/share/opencode/tool-output")
    os.makedirs(out_dir, exist_ok=True)
    found_path = os.path.join(out_dir, "nvidia_reply_found.json")

    print(
        f"{now()} Poller started for conv={args.conv}, user={args.user}, interval={args.interval}s"
    )
    # write pid file
    pid_path = os.path.join(out_dir, "nvidia_poll.pid")
    with open(pid_path, "w") as f:
        f.write(str(os.getpid()))

    try:
        while True:
            try:
                raw = fetch_messages(args.conv, args.workdir)
            except Exception as e:
                print(f"{now()} Error fetching messages: {e}")
                time.sleep(30)
                continue

            try:
                foreign = find_foreign_messages(raw, args.user)
            except Exception as e:
                print(f"{now()} Error parsing messages JSON: {e}")
                time.sleep(30)
                continue

            if foreign:
                result = {"conv": args.conv, "detected_at": now(), "messages": foreign}
                with open(found_path, "w") as f:
                    json.dump(result, f, indent=2)
                print(
                    f"{now()} Found {len(foreign)} foreign message(s) — wrote {found_path}"
                )
                # also print the messages for immediate visibility
                print(json.dumps(result, indent=2))
                return 0

            print(f"{now()} No reply yet; sleeping {args.interval} seconds")
            time.sleep(args.interval)
    finally:
        # cleanup pid file
        try:
            os.remove(pid_path)
        except Exception:
            pass


if __name__ == "__main__":
    main()
