"""
{{AGENT_NAME}} — SentryAgent.ai agent starter
Agent ID: {{AGENT_ID}}

Demonstrates how to authenticate with SentryAgent.ai and issue an OAuth2 access token.
"""

import os
import sys
import requests
from dotenv import load_dotenv

load_dotenv()

API_URL = os.environ.get("AGENTIDP_API_URL", "{{API_URL}}")
CLIENT_ID = os.environ.get("AGENTIDP_CLIENT_ID", "")
CLIENT_SECRET = os.environ.get("AGENTIDP_CLIENT_SECRET", "")

if not CLIENT_ID or not CLIENT_SECRET:
    print("Error: AGENTIDP_CLIENT_ID and AGENTIDP_CLIENT_SECRET must be set in .env")
    sys.exit(1)

print(f"Issuing token for agent {{AGENT_ID}} at {API_URL} ...")

response = requests.post(
    f"{API_URL}/api/v1/token",
    data={
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope": "agents:read",
    },
)

if not response.ok:
    print(f"Token issuance failed: {response.text}")
    sys.exit(1)

token = response.json()
print("✓ Token issued successfully!")
print(f"  Token type: Bearer")
print(f"  Expires in: {token['expires_in']}s")
print(f"  Token (first 20 chars): {token['access_token'][:20]}...")
