fn absolute_url(base, location) {
    if location.starts_with("http://") { return location }
    if location.starts_with("https://") { return location }
    if location.starts_with("/") { return "https://realm.micro1.ai" + location }
    return base + "/" + location
}

fn fetch_login(url) {
    let first = http_get(url)
    if first.is_err() { return first }
    let page = first.unwrap()
    if page.status == 301 || page.status == 302 {
        let next = absolute_url(url, page.headers.location)
        println("redirect: " + next)
        return http_get(next)
    }
    return first
}

fn first_script_src(html) {
    let parts = html.split("<script")
    if parts.len() < 2 { return nil }
    let attrs = parts[1].split(">")[0]
    let src_parts = attrs.split("src=\"")
    if src_parts.len() < 2 { return nil }
    return src_parts[1].split("\"")[0]
}

fn prefix(text, count) {
    let mut out = ""
    let mut i = 0
    while i < count && i < text.len() {
        out = out + text[i]
        i = i + 1
    }
    return out
}

fn main() {
    let url = "https://realm.micro1.ai/login"
    let page = fetch_login(url).unwrap()
    let script_url = absolute_url(url, first_script_src(page.body))
    println("external script: " + script_url)
    let source = http_get(script_url).unwrap().body
    println("script bytes: " + str(source.len()))
    println("has arrow: " + str(source.contains("=>")))
    println("has class: " + str(source.contains("class ")))
    println("has optional chaining: " + str(source.contains("?.")))
    println("has nullish coalescing: " + str(source.contains("??")))
    println("has dynamic import: " + str(source.contains("import(")))
    println("has spread: " + str(source.contains("...")))
    println("has template strings: " + str(source.contains("`")))
    println(prefix(source, 400))
}
