// tools/install/el-install.el — El SDK installer
//
// Downloads and installs the El SDK from the latest Gitea release.
//
// Usage:
//   el-install             # installs to ~/.el (default prefix)
//   el-install /opt/el     # installs to custom prefix
//
// After installation, add to your shell rc:
//   export PATH="$HOME/.el/bin:$PATH"
//   export EL_HOME="$HOME/.el"

// ── Constants ─────────────────────────────────────────────────────────────────

fn gitea_releases_url() -> String {
    return "https://git.neuralplatform.ai/api/v1/repos/neuron-technologies/el/releases/tags/latest"
}

fn sdk_asset_name() -> String {
    return "el-sdk-latest.tar.gz"
}

// ── Helpers ───────────────────────────────────────────────────────────────────

// find_asset_url scans the Gitea release JSON for the asset named target_name
// and returns its browser_download_url. Returns "" if not found.
fn find_asset_url(release_json: String, target_name: String) -> String {
    let assets_raw: String = json_get_raw(release_json, "assets")
    if str_eq(assets_raw, "") {
        return ""
    }
    let n: Int = json_array_len(assets_raw)
    let i: Int = 0
    while i < n {
        let asset: String = json_array_get(assets_raw, i)
        let name: String = json_get(asset, "name")
        if str_eq(name, target_name) {
            return json_get(asset, "browser_download_url")
        }
        let i = i + 1
    }
    return ""
}

// ── Main ──────────────────────────────────────────────────────────────────────

fn main() -> Void {
    // 1. Determine install prefix
    let argv: [String] = args()
    let home: String = env("HOME")

    let prefix: String = home + "/.el"
    let argc: Int = el_list_len(argv)
    // argv[0] is the program name; argv[1] is the first user argument
    if argc > 1 {
        let first_arg: String = el_list_get(argv, 1)
        if !str_eq(first_arg, "") {
            let prefix = first_arg
        }
    }

    let bin_dir: String     = prefix + "/bin"
    let runtime_dir: String = prefix + "/runtime"

    println("El SDK installer")
    println("  prefix  : " + prefix)

    // 2. Create directory structure
    let ok_bin: Bool = fs_mkdir(bin_dir)
    if !ok_bin {
        // fs_mkdir returns false if dir already exists on some impls; try exec
        exec("mkdir -p " + bin_dir)
    }
    let ok_rt: Bool = fs_mkdir(runtime_dir)
    if !ok_rt {
        exec("mkdir -p " + runtime_dir)
    }
    // Ensure both dirs exist via exec regardless
    exec("mkdir -p " + bin_dir + " " + runtime_dir)

    // 3. Fetch release metadata from Gitea API
    println("  Fetching release metadata...")
    let release_json: String = http_get(gitea_releases_url())
    if str_eq(release_json, "") {
        println("Error: failed to fetch release metadata from Gitea")
        exit_program(1)
    }

    // 4. Find the SDK tarball download URL
    let download_url: String = find_asset_url(release_json, sdk_asset_name())
    if str_eq(download_url, "") {
        println("Error: asset '" + sdk_asset_name() + "' not found in release")
        exit_program(1)
    }
    println("  Downloading " + sdk_asset_name() + "...")

    // 5. Download tarball to a temp file
    let tmp_path: String = "/tmp/el-sdk-latest.tar.gz"
    let headers: Map<String, String> = {}
    let downloaded: Bool = http_get_to_file(download_url, headers, tmp_path)
    if !downloaded {
        println("Error: download failed")
        exit_program(1)
    }

    // 6. Extract into prefix
    println("  Extracting to " + prefix + "...")
    let tar_cmd: String = "tar -xzf " + tmp_path + " -C " + prefix
    let tar_out: String = exec(tar_cmd)
    // Clean up temp file
    exec("rm -f " + tmp_path)

    // 7. Make binaries executable
    exec("chmod +x " + bin_dir + "/*")

    // 8. Print success and shell setup instructions
    println("")
    println("El SDK installed to " + prefix + " — add this to your shell rc:")
    println("  export PATH=\"$HOME/.el/bin:$PATH\"")
    println("  export EL_HOME=\"$HOME/.el\"")
}
