// Static File Server for Lux Website
//
// Usage: lux website/serve.lux
// Then open http://localhost:8080
//
// This demonstrates serving the Lux website using Lux's own HTTP server!

fn main(): Unit with {HttpServer, Console, File} = {
    let port = 8080
    let root = "website"

    HttpServer.listen(port)
    Console.print("Lux website server running at http://localhost:" + toString(port))
    Console.print("Serving files from: " + root)
    Console.print("Press Ctrl+C to stop")
    Console.print("")

    serverLoop(root)
}

fn serverLoop(root: String): Unit with {HttpServer, Console, File} = {
    let req = HttpServer.accept()

    // Log request
    Console.print(req.method + " " + req.path)

    // Only handle GET requests
    if req.method != "GET" then {
        HttpServer.respond(405, "Method Not Allowed")
        serverLoop(root)
    } else {
        serveFile(root, req.path)
        serverLoop(root)
    }
}

fn serveFile(root: String, reqPath: String): Unit with {HttpServer, Console, File} = {
    // Determine file path
    let path = if reqPath == "/" then "/index.html" else reqPath
    let filePath = root + path

    // Try to serve the file
    if File.exists(filePath) then {
        let content = File.read(filePath)
        HttpServer.respond(200, content)
    } else {
        // Try with .html extension for clean URLs
        let htmlPath = filePath + ".html"
        if File.exists(htmlPath) then {
            let content = File.read(htmlPath)
            HttpServer.respond(200, content)
        } else {
            // Try index.html for directory paths
            let indexPath = filePath + "/index.html"
            if File.exists(indexPath) then {
                let content = File.read(indexPath)
                HttpServer.respond(200, content)
            } else {
                Console.print("  -> 404 Not Found: " + filePath)
                HttpServer.respond(404, "Not Found: " + reqPath)
            }
        }
    }
}

let output = run main() with {}
