#!/usr/bin/env python3
"""
APEX High-Frequency x402 Loop Client & Bot Starter (Python 3.10+)

Install:
    pip install httpx
    # Optional for per-call Base USDC x402 settlement:
    pip install "x402[httpx,evm]"

Quickstart (Try Free — 1 real call/day/IP, zero wallet needed):
    python3 apex_loop_bot.py --once

Quickstart (24/7 Prepaid Pass Loop — 0 gas, <20ms/call):
    APEX_API_KEY=apx_... python3 apex_loop_bot.py --loop --interval 15

Note: Always sends a clean User-Agent (not Python-urllib) for CDN compatibility.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time
from typing import Any, Dict, Optional

import httpx

BASE_URL = os.environ.get("APEX_BASE_URL", "https://apexfaucet.xyz").rstrip("/")
USER_AGENT = "apex-loop-python/1.0"


class ApexLoopClient:
    def __init__(
        self,
        api_pass: Optional[str] = None,
        base_url: str = BASE_URL,
        try_free_first: bool = True,
        timeout: float = 15.0,
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.api_pass = api_pass or os.environ.get("APEX_API_KEY") or os.environ.get("APEX_PASS") or ""
        self.try_free_first = try_free_first
        self._free_used: set[str] = set()
        self.last_pass_balance_usd: Optional[float] = None
        self._client = httpx.Client(
            timeout=timeout,
            headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
        )

    def close(self) -> None:
        self._client.close()

    def call(self, slug: str, params: Optional[Dict[str, Any]] = None, method: str = "GET") -> Dict[str, Any]:
        params = {k: v for k, v in (params or {}).items() if v is not None and v != ""}
        method = method.upper()

        # 1. Try 1 free real sample/day/IP if no pass is configured yet
        if self.try_free_first and not self.api_pass and slug not in self._free_used:
            url = f"{self.base_url}/api/free/{slug}"
            r = self._client.post(url, json=params) if method == "POST" else self._client.get(url, params=params)
            if r.status_code == 200:
                self._free_used.add(slug)
                return r.json()
            if r.status_code in (402, 404, 429):
                self._free_used.add(slug)

        # 2. Call /api/x402/<slug> with X-APEX-PASS (or inspect 402 terms)
        url = f"{self.base_url}/api/x402/{slug}"
        headers = {"X-APEX-PASS": self.api_pass} if self.api_pass else {}
        r = (
            self._client.post(url, json=params, headers=headers)
            if method == "POST"
            else self._client.get(url, params=params, headers=headers)
        )
        bal = r.headers.get("x-apex-pass-balance")
        if bal is not None:
            try:
                self.last_pass_balance_usd = float(bal)
            except ValueError:
                pass
        if r.status_code == 402:
            body = r.json() if r.content else {}
            return {
                "ok": False,
                "paymentRequired": True,
                "status": 402,
                "starterPassUrl": f"{self.base_url}/api/x402/api-pass-starter",
                "accepts": body.get("accepts", []),
            }
        r.raise_for_status()
        return r.json()

    def token_rug_gate(self, token: str, chain: str = "base", amount_usd: float = 250.0) -> Dict[str, Any]:
        return self.call("token-rug-gate", {"token": token, "chain": chain, "amountUsd": amount_usd})

    def fresh_launches_tick(self, chain: str = "all", safety: str = "safe", limit: int = 10) -> Dict[str, Any]:
        return self.call("fresh-launches-tick", {"chain": chain, "safety": safety, "limit": limit})

    def perp_funding_tick(self, coin: str = "ALL", limit: int = 8) -> Dict[str, Any]:
        return self.call("perp-funding-tick", {"coin": coin, "limit": limit})

    def whale_flow_tick(self, focus: str = "all", limit: int = 8) -> Dict[str, Any]:
        return self.call("whale-flow-tick", {"focus": focus, "limit": limit})

    def dex_spread_tick(self, min_spread_pct: float = 0.5, limit: int = 8) -> Dict[str, Any]:
        return self.call("dex-spread-tick", {"minSpreadPct": min_spread_pct, "limit": limit})

    def gas_bridge_tick(self, to_chain: str = "base", amount_usd: float = 1.0) -> Dict[str, Any]:
        return self.call("gas-bridge-tick", {"toChain": to_chain, "amountUsd": amount_usd})

    def web_clean_extract(self, url: str, max_chars: int = 12000) -> Dict[str, Any]:
        return self.call("web-clean-extract", {"url": url, "maxChars": max_chars}, method="POST")

    def agent_prompt_shield(self, text: str) -> Dict[str, Any]:
        return self.call("agent-prompt-shield", {"text": text}, method="POST")

    def x402_market_tape(self, limit: int = 10) -> Dict[str, Any]:
        return self.call("x402-market-tape", {"limit": limit})

    def agent_signal_board(self, op: str = "read", topic: str = "all", **extra: Any) -> Dict[str, Any]:
        method = "POST" if op == "publish" else "GET"
        return self.call("agent-signal-board", {"op": op, "topic": topic, **extra}, method=method)


def run_once(client: ApexLoopClient) -> int:
    launches = client.fresh_launches_tick(chain="all", safety="safe", limit=3)
    perps = client.perp_funding_tick(limit=3)
    gas = client.gas_bridge_tick(to_chain="base")
    out = {
        "launches_action": launches.get("action"),
        "launches_sample": (launches.get("launches") or [])[:2],
        "perp_action": perps.get("action"),
        "top_funding_arb": (perps.get("funding_arb") or [])[:1],
        "cheapest_gas": gas.get("cheapest_chain"),
        "pass_balance_usd": client.last_pass_balance_usd,
    }
    print(json.dumps(out, indent=2))
    return int(launches.get("next_poll_ms") or 15000)


def main() -> int:
    ap = argparse.ArgumentParser(description="APEX x402 High-Frequency Bot Loop (Python)")
    ap.add_argument("--once", action="store_true", help="Run one tick and exit")
    ap.add_argument("--loop", action="store_true", help="Run continuously honoring next_poll_ms")
    ap.add_argument("--interval", type=int, default=15, help="Fallback poll interval in seconds")
    ap.add_argument("--pass-key", default="", help="Prepaid X-APEX-PASS key (or set APEX_API_KEY)")
    args = ap.parse_args()

    client = ApexLoopClient(api_pass=args.pass_key or None)
    try:
        if args.loop and not args.once:
            while True:
                wait_ms = run_once(client)
                time.sleep(max(3.0, (wait_ms / 1000.0) if wait_ms else float(args.interval)))
        else:
            run_once(client)
    except KeyboardInterrupt:
        return 0
    finally:
        client.close()
    return 0


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