"""Agent loop: repeatedly generate and submit suggestions."""

from __future__ import annotations

import time
import sys

from .client import NbenchClient
from .suggest import run_suggest


def run_agent(
    api_url: str,
    api_key: str,
    project_id: str,
    provider_name: str = "anthropic",
    model: str | None = None,
    interval: int = 300,
) -> None:
    """Run the agent loop: check state, generate suggestion, submit, sleep, repeat."""
    client = NbenchClient(api_url=api_url, api_key=api_key)
    cycle = 0

    print(f"[agent] Starting agent loop (interval={interval}s)")
    print(f"[agent] Project: {project_id}")
    print(f"[agent] Provider: {provider_name}" + (f" / {model}" if model else ""))

    while True:
        cycle += 1
        print(f"\n[agent] === Cycle {cycle} ===")

        try:
            # Pre-flight checks
            try:
                account = client.get_account()
                balance = account.get("balance_usd", 0)
                print(f"[agent] Balance: ${balance:.2f}")
                if balance <= 0:
                    print("[agent] Insufficient balance, waiting...")
                    time.sleep(interval)
                    continue
            except Exception:
                # Account endpoint may not require auth or may not exist yet
                pass

            try:
                queue = client.get_queue(project_id)
                queued_count = sum(1 for s in queue if s.get("status") == "queued")
                print(f"[agent] Queue depth: {queued_count}")
                if queued_count >= 5:
                    print("[agent] Queue full, waiting...")
                    time.sleep(interval)
                    continue
            except Exception:
                pass

            # Generate and submit suggestion
            result = run_suggest(
                api_url=api_url,
                api_key=api_key,
                project_id=project_id,
                provider_name=provider_name,
                model=model,
            )
            suggestion_id = result.get("id", "?")
            print(f"[agent] Submitted suggestion #{suggestion_id}")

        except KeyboardInterrupt:
            print("\n[agent] Interrupted, exiting.")
            sys.exit(0)
        except Exception as exc:
            print(f"[agent] Error: {exc}")

        try:
            time.sleep(interval)
        except KeyboardInterrupt:
            print("\n[agent] Interrupted, exiting.")
            sys.exit(0)
