"""One-shot: napraw manifest.json dla istniejącego OTA update'u.

Bugs:
  1. Windows publish wpisywał `assets\<hash>` (os.sep) do URL'i.
  2. URL hosta ustawiony na 'goon-app.crawlbot.pl:8443' który nie ma DNS —
     mobile nie pobierze assetów. Właściwy host: api.goon-foss.org (port 443).

Normalizujemy `\` → `/` i podmieniamy hosta na CORRECT_HOST.
"""
import json
import sys

CORRECT_HOST_PREFIX = "https://api.goon-foss.org/expo-updates/asset"
WRONG_HOST_PREFIXES = [
    "https://goon-app.crawlbot.pl:8443/expo-updates/asset",
]


def fix_url(u: str) -> tuple[str, bool]:
    new = u.replace("\\", "/")
    for wrong in WRONG_HOST_PREFIXES:
        if new.startswith(wrong):
            new = new.replace(wrong, CORRECT_HOST_PREFIX, 1)
            break
    return new, new != u


def main() -> int:
    if len(sys.argv) != 2:
        print("usage: _patch_manifest.py <manifest.json path>")
        return 1

    path = sys.argv[1]
    m = json.load(open(path))
    fixed = 0
    for a in m.get("assets", []):
        new, ch = fix_url(a["url"])
        if ch:
            a["url"] = new
            fixed += 1
    la = m.get("launchAsset", {})
    if "url" in la:
        new, ch = fix_url(la["url"])
        if ch:
            la["url"] = new
            fixed += 1
    with open(path, "w") as f:
        json.dump(m, f, indent=2)
    print(f"patched {fixed} URLs in {path}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
