// HTTP Server Example
// Run with: cargo run -- examples/http_server.lux
// Then visit: http://localhost:8080/

// Simple request handler
fn handleRequest(req: { method: String, path: String, body: String, headers: List<(String, String)> }): Unit with {Console, HttpServer} = {
    Console.print("Received: " + req.method + " " + req.path)

    // Route based on path
    match req.path {
        "/" => HttpServer.respond(200, "Welcome to Lux HTTP Server!"),
        "/hello" => HttpServer.respond(200, "Hello, World!"),
        "/json" => HttpServer.respondWithHeaders(200, "\{\"message\": \"Hello from Lux!\"\}", [("Content-Type", "application/json")]),
        "/echo" => HttpServer.respond(200, "You sent: " + req.body),
        _ => HttpServer.respond(404, "Not Found: " + req.path)
    }
}

// Handle N requests then stop
fn serveN(n: Int): Unit with {Console, HttpServer} =
    if n <= 0 then {
        Console.print("Server stopping...")
        HttpServer.stop()
    } else {
        let req = HttpServer.accept()
        handleRequest(req)
        serveN(n - 1)
    }

// Main entry point
fn main(): Unit with {Console, HttpServer} = {
    let port = 8080
    Console.print("Starting HTTP server on port " + toString(port) + "...")
    HttpServer.listen(port)
    Console.print("Server listening! Will handle 5 requests then stop.")
    Console.print("Try: curl http://localhost:8080/")
    Console.print("     curl http://localhost:8080/hello")
    Console.print("     curl http://localhost:8080/json")
    Console.print("     curl -X POST -d 'test data' http://localhost:8080/echo")
    serveN(5)
}

// Run main
let output = run main() with {}
