"""
Polymarket US API — authentication (Phase 1, read-only).

Ed25519 request signing per docs.polymarket.us/api-reference/authentication:
  headers: X-PM-Access-Key (key id), X-PM-Timestamp (unix ms),
           X-PM-Signature (base64 Ed25519 sig of `{timestamp}{METHOD}{path}`)
  secret key: base64-decoded, first 32 bytes used as the Ed25519 seed.

This is a SEPARATE platform from polymarket.com (different company, different
market catalog, different auth) -- see project_soccer_pipeline memory. Nothing
here talks to gamma-api.polymarket.com / the existing polymarket_live.py.
"""
import os
import time
import base64
from pathlib import Path
from typing import Optional

import requests
from dotenv import load_dotenv
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

load_dotenv(r'E:\soccer\.env')

API_BASE = "https://api.polymarket.us"
GATEWAY_BASE = "https://gateway.polymarket.us"  # public, no auth

API_KEY = os.getenv("POLYUS_API_KEY")
SECRET_KEY = os.getenv("POLYUS_SECRET_KEY")

_priv_key_cache: Optional[Ed25519PrivateKey] = None


def _load_private_key() -> Ed25519PrivateKey:
    global _priv_key_cache
    if _priv_key_cache is not None:
        return _priv_key_cache
    if not SECRET_KEY:
        raise RuntimeError("POLYUS_SECRET_KEY not set in .env")
    raw = base64.b64decode(SECRET_KEY)[:32]
    _priv_key_cache = Ed25519PrivateKey.from_private_bytes(raw)
    return _priv_key_cache


def _auth_headers(method: str, path: str) -> dict:
    if not API_KEY:
        raise RuntimeError("POLYUS_API_KEY not set in .env")
    ts = str(int(time.time() * 1000))
    message = f"{ts}{method.upper()}{path}"
    key = _load_private_key()
    sig = base64.b64encode(key.sign(message.encode("utf-8"))).decode("utf-8")
    return {
        "X-PM-Access-Key": API_KEY,
        "X-PM-Timestamp": ts,
        "X-PM-Signature": sig,
        "Accept": "application/json",
    }


def _get(path: str, params: Optional[dict] = None) -> dict:
    headers = _auth_headers("GET", path)
    r = requests.get(API_BASE + path, headers=headers, params=params, timeout=15)
    if r.status_code != 200:
        raise RuntimeError(f"GET {path} -> {r.status_code}: {r.text}")
    return r.json()


def get_account_balances() -> dict:
    return _get("/v1/account/balances")


def get_open_orders() -> dict:
    return _get("/v1/orders/open")


def get_positions() -> dict:
    return _get("/v1/portfolio/positions")


if __name__ == "__main__":
    import json
    print("=== Phase 1: Polymarket US auth check ===")
    print(f"API key: {API_KEY[:8]}..." if API_KEY else "API key: MISSING")

    print("\n[1/3] Checking account balances (Ed25519 signed request)...")
    bal = get_account_balances()
    print(json.dumps(bal, indent=2))

    print("\n[2/3] Checking open orders...")
    orders = get_open_orders()
    print(json.dumps(orders, indent=2)[:1000])

    print("\n[3/3] Checking positions...")
    pos = get_positions()
    print(json.dumps(pos, indent=2)[:1000])

    print("\nPhase 1 OK -- read-only auth verified. No orders placed.")
