import argparse
import configparser
import json
import sys
import urllib.request
from pathlib import Path

INI_FILE = Path("latestversion.ini")
PYTHON_API = "https://endoflife.date/api/v1/products/python"
CAESIUM_API = "https://api.github.com/repos/Lymphatus/caesium-clt/tags"

EXIT_NO_UPDATE = 0
EXIT_UPDATE_AVAILABLE = 10
EXIT_ERROR = 20


def fetch_json(url):
    with urllib.request.urlopen(url, timeout=15) as r:
        return json.loads(r.read().decode("utf-8"))


def load_ini():
    cfg = configparser.ConfigParser()
    cfg.read(INI_FILE, encoding="utf-8")
    return cfg


def save_ini(cfg):
    with open(INI_FILE, "w", encoding="utf-8") as f:
        cfg.write(f)


def check_python(cfg, result):
    used = cfg["DEFAULT"].get("python_used_version", "").strip()
    major_minor = ".".join(used.split(".")[:2])

    data = fetch_json(PYTHON_API)
    releases = data.get("result", {}).get("releases", [])

    for rel in releases:
        if rel.get("name") != major_minor:
            continue

        latest = rel.get("latest", {}).get("name", "")
        is_maintained = rel.get("isMaintained", True)

        cfg["DEFAULT"]["python_latest_version"] = latest

        if used != latest:
            result["updates"].append({
                "tool": "python",
                "used": used,
                "latest": latest,
                "maintained": is_maintained,
                "url": (
                    f"https://www.python.org/ftp/python/{latest}/"
                    f"python-{latest}-embed-amd64.zip"
                )
            })


def check_caesium(cfg, result):
    used = cfg["DEFAULT"].get("caesiumclt_used_version", "").strip()

    tags = fetch_json(CAESIUM_API)
    latest = tags[0]["name"]

    cfg["DEFAULT"]["caesiumclt_latest_version"] = latest

    if used != latest:
        result["updates"].append({
            "tool": "caesiumclt",
            "used": used,
            "latest": latest,
            "maintained": True,
            "url": (
                f"https://github.com/Lymphatus/caesium-clt/releases/download/{latest}/"
                f"caesiumclt-{latest}-x86_64-pc-windows-msvc.zip"
            )
        })


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--yes", action="store_true")
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    cfg = load_ini()
    result = {"updates": []}

    try:
        check_python(cfg, result)
        check_caesium(cfg, result)
    except Exception as e:
        print(f"ERROR: {e}")
        sys.exit(EXIT_ERROR)

    save_ini(cfg)

    if args.json:
        print(json.dumps(result, indent=2))
    else:
        for u in result["updates"]:
            print(
                f"{u['tool'].capitalize()}: aktuell genutzt {u['used']}, "
                f"neu {u['latest']}, download?"
            )
            print(f"{u['tool'].upper()}_DOWNLOAD={u['url']}")

            if not u["maintained"]:
                print(
                    f"WARNING: Achtung Version {u['latest']} "
                    "wird nicht mehr gewartet!"
                )

    sys.exit(EXIT_UPDATE_AVAILABLE if result["updates"] else EXIT_NO_UPDATE)


if __name__ == "__main__":
    main()