#!/usr/bin/env python3
"""Paper arbitrage scanner for MAX and BitoPro TWD markets.

Stdlib only. No orders are placed. Logs executable edges to CSV.

MAX is read from real order books. BitoPro is read from its public
tickers endpoint (last price) because its order-book endpoint is not
publicly reachable; cross-venue rows are therefore marked approx.
"""
from __future__ import annotations

import argparse
import csv
import json
import os
import sys
import time
import urllib.request
from typing import Dict, List, Optional, Tuple

MAX_API = "https://max-api.maicoin.com/api/v2"
BITO_API = "https://api.bitopro.com/v3"

DEFAULT_ASSETS = ["BTC", "ETH", "XRP", "SOL"]
CROSS_PAIRS = [("btctwd", "btc_twd"), ("ethtwd", "eth_twd"), ("usdttwd", "usdt_twd")]


def http_json(url: str, timeout: float = 10.0, retries: int = 2):
    last = None
    for _ in range(retries + 1):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "tw-arb-scan/1.0"})
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode())
        except Exception as exc:
            last = exc
            time.sleep(0.3)
    raise last


def max_depth(market: str, limit: int = 20) -> Dict:
    d = http_json(f"{MAX_API}/depth?market={market}&limit={limit}")
    return {
        "asks": [[float(p), float(q)] for p, q in d.get("asks", [])],
        "bids": [[float(p), float(q)] for p, q in d.get("bids", [])],
        "ts": d.get("timestamp"),
    }


def book_ok(d: Dict, max_spread: float, min_top_notional: float) -> bool:
    asks, bids = d.get("asks"), d.get("bids")
    if not asks or not bids:
        return False
    a, b = asks[0], bids[0]
    if a[0] <= 0 or b[0] <= 0 or a[0] < b[0]:
        return False
    mid = (a[0] + b[0]) / 2.0
    if (a[0] - b[0]) / mid > max_spread:
        return False
    if a[0] * a[1] < min_top_notional or b[0] * b[1] < min_top_notional:
        return False
    return True


def buy_with_quote(asks: List[List[float]], quote_budget: float) -> Tuple[float, bool]:
    base_got = 0.0
    quote_spent = 0.0
    for price, size in asks:
        level = price * size
        if quote_spent + level <= quote_budget:
            base_got += size
            quote_spent += level
        else:
            remaining = quote_budget - quote_spent
            if remaining > 0 and price > 0:
                base_got += remaining / price
                quote_spent += remaining
            break
    return base_got, quote_spent >= quote_budget * (1 - 1e-9)


def sell_for_quote(bids: List[List[float]], base_amount: float) -> Tuple[float, bool]:
    remaining = base_amount
    quote_got = 0.0
    for price, size in bids:
        take = min(size, remaining)
        quote_got += take * price
        remaining -= take
        if remaining <= 1e-12:
            break
    return quote_got, remaining <= 1e-9


def triangle_edge(asset: str, depths: Dict, clip_twd: float, fee: float,
                  max_spread: float, min_top_notional: float):
    twd_m = f"{asset.lower()}twd"
    usdt_m = f"{asset.lower()}usdt"
    if any(m not in depths for m in ("usdttwd", twd_m, usdt_m)):
        return None
    for m in ("usdttwd", twd_m, usdt_m):
        if not book_ok(depths[m], max_spread, min_top_notional):
            return None

    keep = 1.0 - fee
    d_ut, d_tw, d_us = depths["usdttwd"], depths[twd_m], depths[usdt_m]
    rows = []

    usdt, c1 = buy_with_quote(d_ut["asks"], clip_twd)
    alt, c2 = buy_with_quote(d_us["asks"], usdt * keep) if usdt > 0 else (0.0, False)
    twd_out, c3 = sell_for_quote(d_tw["bids"], alt * keep) if alt > 0 else (0.0, False)
    rows.append(("usdt_in", (twd_out * keep / clip_twd - 1.0) * 100, c1 and c2 and c3))

    alt2, d1 = buy_with_quote(d_tw["asks"], clip_twd)
    usdt2, d2 = sell_for_quote(d_us["bids"], alt2 * keep) if alt2 > 0 else (0.0, False)
    twd_out2, d3 = sell_for_quote(d_ut["bids"], usdt2 * keep) if usdt2 > 0 else (0.0, False)
    rows.append(("alt_in", (twd_out2 * keep / clip_twd - 1.0) * 100, d1 and d2 and d3))
    return rows


def scan_once(assets, clip_twd, max_fee, bito_fee, depth_limit, buffer, max_spread, min_top):
    tickers = http_json(f"{MAX_API}/tickers")
    bito = {x["pair"]: x for x in http_json(f"{BITO_API}/tickers").get("data", [])}

    depths = {}
    for m in ["usdttwd"] + [f"{a.lower()}{q}" for a in assets for q in ("twd", "usdt")]:
        if m not in tickers:
            continue
        try:
            depths[m] = max_depth(m, limit=depth_limit)
        except Exception:
            continue
        time.sleep(0.05)

    rows, skipped = [], []
    now = int(time.time())
    for a in assets:
        raw = triangle_edge(a, depths, clip_twd, 0.0, max_spread, min_top)
        netf = triangle_edge(a, depths, clip_twd, max_fee, max_spread, min_top)
        if not raw or not netf:
            skipped.append(a)
            continue
        for (direction, gross, complete), (_, netfee, _) in zip(raw, netf):
            ok = int(bool(complete) and abs(gross) <= 5.0)
            rows.append(dict(ts=now, kind="triangle", venue="MAX", asset=a,
                             direction=direction, clip_twd=clip_twd,
                             gross_pct=round(gross, 4), fee_pct=round(gross - netfee, 4),
                             net_pct=round(netfee - buffer * 100, 4), complete=int(complete),
                             ok=ok, note="max_depth"))

    for max_m, bito_p in CROSS_PAIRS:
        if max_m not in tickers or bito_p not in bito:
            continue
        try:
            mx_bid, mx_ask = float(tickers[max_m]["buy"]), float(tickers[max_m]["sell"])
            bt = float(bito[bito_p]["lastPrice"])
        except Exception:
            continue
        fee2 = (max_fee + bito_fee) * 100
        for direction, gross in (("sell_max_buy_bito", (mx_bid / bt - 1) * 100),
                                 ("buy_max_sell_bito", (bt / mx_ask - 1) * 100)):
            rows.append(dict(ts=now, kind="cross", venue="MAX/BitoPro", asset=max_m,
                             direction=direction, clip_twd=clip_twd,
                             gross_pct=round(gross, 4), fee_pct=round(fee2, 4),
                             net_pct=round(gross - fee2 - buffer * 100, 4), complete=-1,
                             ok=1, note="approx_bito_last"))
    return rows, skipped


def main() -> int:
    ap = argparse.ArgumentParser(description="MAX/BitoPro TWD arbitrage paper scanner")
    ap.add_argument("--assets", default=",".join(DEFAULT_ASSETS))
    ap.add_argument("--clip", type=float, default=50000.0, help="starting TWD notional")
    ap.add_argument("--interval", type=float, default=10.0)
    ap.add_argument("--cycles", type=int, default=0, help="0 = run forever")
    ap.add_argument("--max-fee", type=float, default=0.0015)
    ap.add_argument("--bito-fee", type=float, default=0.0015)
    ap.add_argument("--buffer", type=float, default=0.0005)
    ap.add_argument("--max-leg-spread", type=float, default=0.02)
    ap.add_argument("--min-top-notional", type=float, default=0.0)
    ap.add_argument("--depth-limit", type=int, default=20)
    ap.add_argument("--out", default="logs/scan.csv")
    args = ap.parse_args()

    assets = [a.strip().upper() for a in args.assets.split(",") if a.strip()]
    out = args.out if os.path.isabs(args.out) else os.path.join(
        os.path.dirname(os.path.abspath(__file__)), args.out)
    os.makedirs(os.path.dirname(out), exist_ok=True)
    header = not os.path.exists(out)

    print(f"scanning MAX/BitoPro | assets={assets} | clip={args.clip:.0f} TWD")
    print(f"fees max={args.max_fee:.4f} bito={args.bito_fee:.4f} buffer={args.buffer:.4f} "
          f"| leg gate: spread<={args.max_leg_spread:.1%} top>={args.min_top_notional:.0f}")
    print("NO ORDERS ARE PLACED. BitoPro = last price (approx); MAX = real depth.\n")

    fh = open(out, "a", newline="")
    fields = ["ts", "kind", "venue", "asset", "direction", "clip_twd", "gross_pct",
              "fee_pct", "net_pct", "complete", "ok", "note"]
    w = csv.DictWriter(fh, fieldnames=fields)
    if header:
        w.writeheader()

    cycle = 0
    try:
        while True:
            cycle += 1
            try:
                rows, skipped = scan_once(assets, args.clip, args.max_fee, args.bito_fee,
                                          args.depth_limit, args.buffer,
                                          args.max_leg_spread, args.min_top_notional)
            except Exception as exc:
                print(f"[cycle {cycle}] error: {exc}")
                time.sleep(args.interval)
                continue
            w.writerows(rows)
            fh.flush()

            tri = sorted((r for r in rows if r["kind"] == "triangle" and r["ok"]),
                         key=lambda r: r["net_pct"], reverse=True)
            crs = sorted((r for r in rows if r["kind"] == "cross"),
                         key=lambda r: r["net_pct"], reverse=True)
            stamp = time.strftime("%H:%M:%S")
            msg = f"[{stamp}] c{cycle} tri_ok={len(tri)}"
            if skipped:
                msg += f" illiquid={','.join(skipped)}"
            if tri:
                b = tri[0]
                msg += f" | bestTri {b['asset']}:{b['direction']} {b['net_pct']:+.3f}%"
            if crs:
                b = crs[0]
                msg += f" | bestX {b['asset']}:{b['direction']} {b['net_pct']:+.3f}%"
            pos = sum(1 for r in rows if r["ok"] and r["net_pct"] > 0)
            msg += f" | net>0={pos}"
            print(msg)

            if args.cycles and cycle >= args.cycles:
                break
            time.sleep(args.interval)
    finally:
        fh.close()
        print(f"\nlog -> {out}")
    return 0


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