#!/usr/bin/env -S julia --project=. --startup-file=no

using DependencyAtlas

function parse_args(args)
    host = get(ENV, "DEPATLAS_HOST", "127.0.0.1")
    port = try
        parse(Int, get(ENV, "DEPATLAS_PORT", "8099"))
    catch
        8099
    end
    store_root = get(ENV, "DEPATLAS_STORE", ".depatlas-store")
    static_root = String(strip(get(ENV, "DEPATLAS_STATIC_ROOT", joinpath(@__DIR__, "..", "dist"))))
    static = lowercase(strip(get(ENV, "DEPATLAS_STATIC", ""))) in ("1", "true", "yes", "on")

    i = 1
    while i <= length(args)
        if args[i] == "--host" && i < length(args)
            host = args[i+1]
            i += 2
        elseif args[i] == "--port" && i < length(args)
            port = parse(Int, args[i+1])
            i += 2
        elseif args[i] == "--store" && i < length(args)
            store_root = args[i+1]
            i += 2
        elseif args[i] == "--static-root" && i < length(args)
            static_root = String(strip(args[i+1]))
            i += 2
        elseif args[i] == "--static"
            static = true
            i += 1
        elseif args[i] in ("-h", "--help")
            println("""
            DependencyAtlas API server

            Usage:
              ./bin/depatlas-server [--host 127.0.0.1] [--port 8099] [--store .depatlas-store] [--static] [--static-root dist]
            """)
            exit(0)
        else
            error("Unknown argument: $(args[i])")
        end
    end

    return (; host, port, store_root, static, static_root)
end

(; host, port, store_root, static, static_root) = parse_args(ARGS)
store = default_store(root=store_root)
println("Starting DependencyAtlas on http://$(host):$(port)")
if static
    static_root_abs = abspath(static_root)
    println("Serving static files from: $(static_root_abs)")
    if !isdir(static_root_abs)
        @warn "Static root does not exist; static file serving is enabled but files are unavailable." static_root = static_root_abs
    elseif isempty(readdir(static_root_abs))
        @warn "Static root is empty; static file serving is enabled but no files were found." static_root = static_root_abs
    end
end
try
    start_server(; host, port, store, static, static_root, async=false)
catch err
    if err isa InterruptException
        println("Shutting down (Ctrl-C).")
        exit(0)
    end
    rethrow()
end
