#!/usr/bin/env python3
"""Post-deploy smoke: login + optional batch endpoint (run on server)."""
import json
import os
import sys
import urllib.error
import urllib.request

BASE = os.environ.get("NEXUS_TEST_BASE", "http://127.0.0.1:8600")
USER = os.environ.get("NEXUS_TEST_ADMIN_USER", "admin")
PASSWORD = os.environ.get("NEXUS_TEST_ADMIN_PASSWORD", "")


def post(path: str, body: dict, headers: dict | None = None) -> dict:
    h = {"Content-Type": "application/json", **(headers or {})}
    req = urllib.request.Request(
        f"{BASE}{path}",
        data=json.dumps(body).encode(),
        headers=h,
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.load(resp)


def main() -> int:
    if not PASSWORD:
        print("SKIP: set NEXUS_TEST_ADMIN_PASSWORD", file=sys.stderr)
        return 2
    login = post("/api/auth/login", {"username": USER, "password": PASSWORD})
    token = login.get("access_token")
    exp = login.get("expires_in")
    print(f"login ok expires_in={exp}")
    if exp != 3600:
        print(f"WARN: expected expires_in=3600, got {exp}")
    if not token:
        print("FAIL: no access_token")
        return 1
    # Minimal authenticated call
    req = urllib.request.Request(
        f"{BASE}/api/servers/stats",
        headers={"Authorization": f"Bearer {token}"},
    )
    with urllib.request.urlopen(req, timeout=30) as resp:
        stats = json.load(resp)
    print(f"servers/stats ok keys={list(stats.keys())[:5]}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except urllib.error.HTTPError as e:
        print(f"HTTP {e.code}: {e.read().decode()[:500]}", file=sys.stderr)
        raise SystemExit(1)
