import io.github.cdimascio.dotenv.Dotenv;
import okhttp3.*;
import com.google.gson.*;

/**
 * {{AGENT_NAME}} — SentryAgent.ai agent starter (Java)
 * Agent ID: {{AGENT_ID}}
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load();

        String apiUrl = dotenv.get("AGENTIDP_API_URL", "{{API_URL}}");
        String clientId = dotenv.get("AGENTIDP_CLIENT_ID", "");
        String clientSecret = dotenv.get("AGENTIDP_CLIENT_SECRET", "");

        if (clientId.isEmpty() || clientSecret.isEmpty()) {
            System.err.println("Error: AGENTIDP_CLIENT_ID and AGENTIDP_CLIENT_SECRET must be set");
            System.exit(1);
        }

        System.out.println("Issuing token for agent {{AGENT_ID}} at " + apiUrl + " ...");

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("grant_type", "client_credentials")
                .add("client_id", clientId)
                .add("client_secret", clientSecret)
                .add("scope", "agents:read")
                .build();

        Request request = new Request.Builder()
                .url(apiUrl + "/api/v1/token")
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                System.err.println("Token issuance failed: HTTP " + response.code());
                System.exit(1);
            }
            JsonObject token = JsonParser.parseString(response.body().string()).getAsJsonObject();
            String accessToken = token.get("access_token").getAsString();
            int expiresIn = token.get("expires_in").getAsInt();
            System.out.println("✓ Token issued successfully!");
            System.out.println("  Expires in: " + expiresIn + "s");
            System.out.println("  Token (first 20 chars): " + accessToken.substring(0, Math.min(20, accessToken.length())) + "...");
        }
    }
}
