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 first_script_src(html) {
    return html.split("<script")[1].split("src=\"")[1].split("\"")[0]
}

fn inline_first_script(html, source) {
    let parts = html.split("<script")
    let tag = "<script" + parts[1].split("</script>")[0] + "</script>"
    return html.replace(tag, "<script>" + source + "</script>")
}

fn main() {
    let login = http_get("https://realm.micro1.ai/login").unwrap()
    let redirected = http_get(absolute_url("https://realm.micro1.ai/login", login.headers.location)).unwrap()
    let src = absolute_url("https://realm.micro1.ai/login", first_script_src(redirected.body))
    let source = http_get(src).unwrap().body
    let needle = "throw Error(on(130,e==null?e:typeof e,\"\"))"
    let patched = "throw Error(on(130,e==null?e:(typeof e+\":\"+(typeof Object<\"u\"&&Object.keys?Object.keys(e).join(\",\"):\"no-keys\")+\":\"+String(e.$$typeof)+\":provider=\"+(e.$$typeof===EKe)+\":context=\"+(e.$$typeof===jKe)),\"\"))"
    println("patch hits: " + str(source.split(needle).len() - 1))
    println(browser_run_scripts(inline_first_script(redirected.body, source.replace(needle, patched))))
}
