#!/usr/bin/env python3
"""Helper script to update requirements."""
import json
import os
import sys

import requests

ROOT = os.path.dirname(os.path.abspath(f"{__file__}/.."))

PKG_PATH = PACKAGE = None
for fname in os.listdir(f"{ROOT}/custom_components"):
    if fname != "__pycache__" and os.path.isdir(f"{ROOT}/custom_components/{fname}"):
        PACKAGE = fname
        PKG_PATH = f"{ROOT}/custom_components/{PACKAGE}"
        break

if not PACKAGE:
    print("Package not found.")
    sys.exit(1)


def get_package(requre: str) -> str:
    """Extract package name from requirement."""
    return requre.split(">")[0].split("<")[0].split("!")[0].split("=")[0].split("~")[0]


harequire = ["homeassistant"]
request = requests.get(
    "https://raw.githubusercontent.com/home-assistant/core/dev/requirements.txt",
    timeout=10
)
request = request.text.split("\n")
for req in request:
    if "=" in req:
        harequire.append(get_package(req))

with open(f"{PKG_PATH}/manifest.json", encoding="utf8") as manifest:
    manifest = json.load(manifest)

with open(f"{ROOT}/requirements.txt", encoding="utf8") as requirements:
    tmp = requirements.readlines()
    requirements = []
    for req in tmp:
        pkg = get_package(req)
        if pkg not in harequire:
            requirements.append(req.replace("\n", ""))
    manifest["requirements"] = requirements

with open(f"{PKG_PATH}/manifest.json", "w", encoding="utf8") as manifestfile:
    manifestfile.write(json.dumps(manifest, indent=4))
