/**
 * ═══════════════════════════════════════════════════════════
 * 🐍 OPHION - Example Java Application
 * This app is automatically instrumented by OpenTelemetry Java Agent
 * No code changes needed - just the agent JAR!
 * ═══════════════════════════════════════════════════════════
 */

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

public class Main {
    private static final Logger logger = Logger.getLogger(Main.class.getName());
    private static final int PORT = 8080;

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
        
        // Routes
        server.createContext("/", new HomeHandler());
        server.createContext("/health", new HealthHandler());
        server.createContext("/api/users", new UsersHandler());
        server.createContext("/api/slow", new SlowHandler());
        
        server.setExecutor(Executors.newFixedThreadPool(10));
        server.start();
        
        logger.info("🚀 Java server running on port " + PORT);
        logger.info("📊 OTEL Endpoint: " + System.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"));
        logger.info("🏷️  Service Name: " + System.getenv("OTEL_SERVICE_NAME"));
    }

    static class HomeHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            logger.info("Home endpoint called");
            String response = """
                {
                    "message": "Hello from Java!",
                    "instrumented": true,
                    "otelEndpoint": "%s"
                }
                """.formatted(System.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"));
            sendResponse(exchange, 200, response);
        }
    }

    static class HealthHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = """
                {
                    "status": "healthy",
                    "service": "java-example"
                }
                """;
            sendResponse(exchange, 200, response);
        }
    }

    static class UsersHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            logger.info("Fetching users");
            // Simulate some work
            sleep(10 + (int)(Math.random() * 90));
            String response = """
                [
                    {"id": 1, "name": "Alice"},
                    {"id": 2, "name": "Bob"},
                    {"id": 3, "name": "Charlie"}
                ]
                """;
            sendResponse(exchange, 200, response);
        }
    }

    static class SlowHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            logger.info("Starting slow operation");
            sleep(500);
            logger.info("Slow operation completed");
            String response = """
                {
                    "message": "Slow response",
                    "delay": "500ms"
                }
                """;
            sendResponse(exchange, 200, response);
        }
    }

    private static void sendResponse(HttpExchange exchange, int code, String response) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(code, response.getBytes().length);
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(response.getBytes());
        }
    }

    private static void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
