"""Working reference: counter-pattern batch runner for vg-coder.

Submits N tasks across M Chrome profiles (Best-of-N parallel). Each task
runs in a fresh AI Studio tab pinned to a specific chromeId. Demonstrates:

  - chromeId pinning (precedence > workerLabel) — required for deterministic routing
  - Counter pattern: close → open → wait-ready → submit → poll → close
  - wait-ready endpoint (avoids 2-loop polling)
  - Cooldown awareness — skip profiles with active rate-limit cooldown
  - Parallel execution via ThreadPoolExecutor
  - Graceful handling of launcher_not_found (404) + quota_exceeded failures

Usage:
    python batch_runner.py --base http://127.0.0.1:6868 \
        --prompt "What is 2+2?" --runs 3 --model gemini-3.1-pro-preview

Or pass multiple prompts via stdin (one per line) + use --parallel-N.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import json
import logging
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
from dataclasses import dataclass
from typing import Optional

log = logging.getLogger("batch-runner")
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%H:%M:%S",
)


# ── HTTP helpers ───────────────────────────────────────────────────────────


_UA = "vg-coder-batch-runner/1.0"


def http_get(base: str, path: str, timeout: int = 30) -> dict:
    req = urllib.request.Request(f"{base}{path}", headers={"User-Agent": _UA})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read())


def http_post(base: str, path: str, body: dict, timeout: int = 30) -> dict:
    req = urllib.request.Request(
        f"{base}{path}",
        data=json.dumps(body).encode(),
        method="POST",
        headers={"Content-Type": "application/json", "User-Agent": _UA},
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        # 404 launcher_not_found / 504 wait_ready_timeout return JSON bodies
        try:
            return {"_http_status": e.code, **json.loads(e.read())}
        except Exception:
            raise


def submit_task(base: str, prompt: str, chrome_id: str,
                meta: Optional[dict] = None, timeout: int = 30) -> str:
    """POST /api/tasks (multipart). Returns task_id.

    Always pin chromeId — server falls back to first launcher if neither
    chromeId nor workerLabel given, which leaks tabs across profiles.
    """
    boundary = f"----b_{uuid.uuid4().hex}"
    body = bytearray()

    def field(name: str, value: str):
        body.extend(f"--{boundary}\r\n".encode())
        body.extend(f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode())
        body.extend(value.encode("utf-8"))
        body.extend(b"\r\n")

    field("prompt", prompt)
    field("chromeId", chrome_id)
    if meta:
        field("meta", json.dumps(meta))
    body.extend(f"--{boundary}--\r\n".encode())

    req = urllib.request.Request(
        f"{base}/api/tasks",
        data=bytes(body),
        method="POST",
        headers={
            "Content-Type": f"multipart/form-data; boundary={boundary}",
            "User-Agent": _UA,
        },
    )
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read())["taskId"]


# ── Counter pattern ────────────────────────────────────────────────────────


@dataclass
class TaskResult:
    chrome_id: str
    task_id: str
    status: str
    duration_ms: Optional[int]
    chat_id: Optional[str]
    actual_model: Optional[str]
    error_code: Optional[str]
    error_message: Optional[str]
    markdown_url: Optional[str]


def run_counter_pattern(base: str, chrome_id: str, prompt: str,
                        model: str, run_idx: int = 1) -> TaskResult:
    """Close → open → wait-ready → submit → poll → close.

    Returns TaskResult — never raises (failures captured in error_code).
    """
    short = chrome_id[:8]
    log.info("[%s] run #%d start", short, run_idx)

    try:
        # 1. Close any existing tabs in this profile (idempotent — close-all)
        http_post(base, "/api/launcher/close-tab", {"chromeId": chrome_id})
        time.sleep(1)

        # 2. Open fresh tab pinned to chromeId. Model lock via URL ?model=.
        open_resp = http_post(base, "/api/launcher/open-tab",
                              {"chromeId": chrome_id, "model": model})
        if open_resp.get("_http_status") == 404:
            return TaskResult(chrome_id, "", "failed", None, None, None,
                              "launcher_not_found",
                              "chromeId not connected", None)
        log.info("[%s] tab opened id=%s actual_model=%s",
                 short, open_resp.get("tabId"), open_resp.get("actual_model"))

        # 3. Wait for launcher email scraped + worker registered idle
        ready = http_post(base, "/api/launcher/wait-ready",
                          {"chromeId": chrome_id, "timeoutMs": 15000})
        if ready.get("_http_status") in (404, 504):
            return TaskResult(chrome_id, "", "failed", None, None, None,
                              ready.get("error", "wait_ready_failed"),
                              "wait-ready did not resolve in time", None)
        log.info("[%s] worker ready email=%s", short, ready.get("worker", {}).get("email"))

        # 4. Submit task
        task_id = submit_task(base, prompt, chrome_id,
                              meta={"run_idx": run_idx})
        log.info("[%s] submitted task=%s", short, task_id)

        # 5. Poll until terminal
        while True:
            time.sleep(3)
            task = http_get(base, f"/api/tasks/{task_id}")
            status = task["status"]
            if status in ("done", "failed", "canceled"):
                break
            log.debug("[%s] task=%s status=%s", short, task_id, status)

        result = TaskResult(
            chrome_id=chrome_id,
            task_id=task_id,
            status=status,
            duration_ms=task.get("timing", {}).get("durationMs"),
            chat_id=task.get("result", {}).get("chatId") if task.get("result") else None,
            actual_model=task.get("result", {}).get("actualModel") if task.get("result") else None,
            error_code=task.get("error", {}).get("code") if task.get("error") else None,
            error_message=task.get("error", {}).get("message") if task.get("error") else None,
            markdown_url=(
                f"{base}/api/tasks/{task_id}/result"
                if status == "done" else None
            ),
        )
        log.info("[%s] %s in %sms%s",
                 short, status, result.duration_ms or "?",
                 f" (error={result.error_code})" if result.error_code else "")

        # 6. Cleanup: close tab (server-side v2.0.83+ does this automatically
        # on rate-limit; explicit close here keeps tab count tight for non-RL
        # failures and lets next iteration start clean).
        http_post(base, "/api/launcher/close-tab", {"chromeId": chrome_id})
        return result

    except Exception as e:
        log.exception("[%s] unexpected error", short)
        return TaskResult(chrome_id, "", "failed", None, None, None,
                          "exception", str(e), None)


# ── Profile picking ────────────────────────────────────────────────────────


def list_available_chromeids(base: str) -> list[dict]:
    """Return routable chromeIds without active rate-limit cooldown.

    Pool = workers ∪ launchers-with-email, deduped by chromeId. See
    INTEGRATION.md §"Pool discovery" — workers are transient (tabs close
    after each task), launchers are persistent. Pulling from one source
    only causes "spam 1 profile" bug after first batch.

    Email filter on launchers excludes tunnel zombies (entries from
    disconnected sessions where chromeId↔email handshake never finished).

    Each entry: { "chromeId": "...", "email": "..." }.
    """
    seen: dict[str, dict] = {}
    # Workers first — live status confirmed
    workers = http_get(base, "/api/workers").get("workers", [])
    for w in workers:
        cid = w.get("chromeId")
        if cid and not w.get("cooldownRemainingMinutes"):
            seen[cid] = {"chromeId": cid, "email": w.get("email")}
    # Launchers with email — persistent + handshake-confirmed
    launchers = http_get(base, "/api/launchers").get("launchers", [])
    for l in launchers:
        cid = l.get("chromeId")
        if (cid and cid not in seen
                and l.get("email")
                and not l.get("cooldownRemainingMinutes")):
            seen[cid] = {"chromeId": cid, "email": l["email"]}
    return list(seen.values())


# ── Main ───────────────────────────────────────────────────────────────────


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--base", default="http://127.0.0.1:6868",
                   help="vg-coder server URL")
    p.add_argument("--prompt", required=True,
                   help="prompt to run (same for all runs)")
    p.add_argument("--runs", type=int, default=3,
                   help="N runs (Best-of-N). Each run uses a different chromeId.")
    p.add_argument("--model", default="gemini-3.1-pro-preview")
    p.add_argument("--parallel", type=int, default=0,
                   help="max concurrent runs (0 = sequential, N = ThreadPoolExecutor(N))")
    args = p.parse_args()

    log.info("vg-coder: %s", args.base)
    log.info("Discovering available profiles ...")
    pool = list_available_chromeids(args.base)
    if not pool:
        log.error("No available chromeIds (all rate-limited or no launcher connected)")
        sys.exit(1)
    log.info("Pool: %d profile(s) — %s", len(pool),
             ", ".join(f"{p['email'] or p['chromeId'][:8]}" for p in pool))

    if args.runs > len(pool):
        log.warning("Requested %d runs but only %d profiles — will reuse profiles "
                    "(sequentially, never concurrently — same chromeId twice "
                    "in parallel would kill the in-flight task via open-tab)",
                    args.runs, len(pool))

    # Assign chromeIds round-robin. Same chromeId may appear in multiple
    # tasks when runs > len(pool); we serialize those via a per-chromeId
    # semaphore so two threads never hit the same profile concurrently.
    # (Calling open-tab on a chromeId that's mid-task closes the busy tab.
    # See INTEGRATION.md §"ChromeId in-flight lock".)
    tasks = [
        (pool[i % len(pool)]["chromeId"], args.prompt, args.model, i + 1)
        for i in range(args.runs)
    ]
    cid_locks: dict[str, threading.Semaphore] = {
        cid: threading.Semaphore(1)
        for cid in {t[0] for t in tasks}
    }

    def run_with_cid_lock(base: str, cid: str, *rest) -> TaskResult:
        with cid_locks[cid]:
            return run_counter_pattern(base, cid, *rest)

    # Execute
    results: list[TaskResult] = []
    if args.parallel and args.parallel > 1:
        # Cap parallel at len(pool) — more threads than profiles just queue
        # behind the cid_locks above, wasting executor slots.
        effective = min(args.parallel, len(pool))
        log.info("Running %d tasks in parallel (max %d, capped to pool size %d)",
                 len(tasks), args.parallel, effective)
        with concurrent.futures.ThreadPoolExecutor(max_workers=effective) as ex:
            futures = [ex.submit(run_with_cid_lock, args.base, *t) for t in tasks]
            for f in concurrent.futures.as_completed(futures):
                results.append(f.result())
    else:
        log.info("Running %d tasks sequentially", len(tasks))
        for t in tasks:
            results.append(run_counter_pattern(args.base, *t))

    # Summary
    log.info("─── Summary ───")
    done = [r for r in results if r.status == "done"]
    failed = [r for r in results if r.status != "done"]
    log.info("done=%d  failed=%d", len(done), len(failed))
    for r in results:
        log.info("  %s  %s (%sms) → %s",
                 r.chrome_id[:8], r.status,
                 r.duration_ms or "?", r.error_code or r.chat_id or "ok")

    sys.exit(0 if not failed else 1)


if __name__ == "__main__":
    main()
