# Pre-launch checks for a key: mode, scopes, expiry, limits, agent readiness and webhook endpoints.
# Exits 1 if a check fails. Run it with the key your server will use. Python 3.9+ with requests.
import os
import sys
from datetime import datetime, timezone

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
required = os.environ.get("REQUIRED_SCOPES", "calls:write,calls:read,analysis:read").split(",")
auth = {"Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}"}
failures = 0


def check(ok, text):
    global failures
    print(f"{'ok  ' if ok else 'FAIL'} {text}")
    failures += 0 if ok else 1


def get(path):
    r = requests.get(f"{base}{path}", headers=auth, timeout=30)
    body = r.json()
    if not r.ok:
        err = body["error"]
        sys.exit(f"{path}: {err['code']}: {err['message']} (request {err['request_id']})")
    return body


ws = get("/workspace")
key = ws["api_key"]
print(f"{ws['name']} ({ws['id']}), key {key['name']} ({key['id']}), {key['environment']} mode")
missing = [s for s in required if s not in key["scopes"]]
check(not missing, f"scopes {', '.join(required)}" + (f" (missing {', '.join(missing)})" if missing else ""))
extra = [s for s in key["scopes"] if s.endswith(":write") and s not in required]
check(not extra, "no write scopes beyond what you need" + (f" (also has {', '.join(extra)})" if extra else ""))
days = float("inf")
if key["expires_at"]:
    expires = datetime.fromisoformat(key["expires_at"].replace("Z", "+00:00"))
    days = (expires - datetime.now(timezone.utc)).total_seconds() / 86400
check(days > 14, f"key expiry {key['expires_at'] or 'never'}" + (" is less than 14 days away: rotate it" if days <= 14 else ""))
print(f"     limits: dial {ws['limits']['rate_limits']['dial']}, daily calls {ws['limits']['daily_call_limit'] or 'none (test mode)'}")

if os.environ.get("AGENT_ID"):
    readiness = get(f"/agents/{os.environ['AGENT_ID']}/readiness")
    reasons = ", ".join(r["code"] for r in readiness["reasons"])
    check(readiness["ready"], f"agent {readiness['agent_id']} ready" + ("" if readiness["ready"] else f": {reasons}"))

if not ws["capabilities"]["webhooks"]:
    check(False, "webhooks are not enabled for this workspace")
elif "webhooks:read" in key["scopes"]:
    endpoints = get("/webhook-endpoints?limit=100")
    enabled = [e for e in endpoints["data"] if e["status"] == "enabled"]
    check(bool(enabled), f"{len(enabled)} enabled webhook endpoint(s) in {key['environment']} mode")
    for e in enabled:
        last = f"{e['last_delivery']['status']} (HTTP {e['last_delivery']['response_status']})" if e["last_delivery"] else "no delivery yet"
        print(f"     {e['url']}: {', '.join(e['events'])}; last delivery {last}")
else:
    print("     skipped webhook endpoint check (key has no webhooks:read)")

sys.exit(1 if failures else 0)
