"""Script to get information needed by .conda/meta.yaml from PyPi JSON API.

This script use get_info to get the info (yes !) and replace_in_file to
write them into .conda/meta.yaml.
Sample call:
python3 .github/get_pypi_info.py -p OpenFisca-Core
"""

import argparse
import re

import requests


def get_info(package_name: str = "") -> dict:
    """Get minimal information needed by .conda/meta.yaml from PyPi JSON API.

    ::package_name:: Name of package to get infos from.
    ::return:: A dict with last_version, url and sha256
    """
    if package_name == "":
        raise ValueError("Package name not provided.")
    url = f"https://pypi.org/pypi/{package_name}/json"
    print(f"Calling {url}")  # noqa: T001
    resp = requests.get(url)
    if resp.status_code != 200:
        raise Exception(f"ERROR calling PyPI ({url}) : {resp}")
    resp = resp.json()
    version = resp["info"]["version"]
    deps_and_version = {}
    for package in resp["info"]["requires_dist"]:
        if "; extra ==" in package:
            continue
        package_name = package.split("(")[0].replace(" ", "")
        package_name = package_name.replace("[pipeline]", "")
        if package_name == "tables":
            package_name = "pytables"
        package_version = (
            re.search("\(([^)]+)", package).group(1).replace(" ", "")  # noqa: W605
            )  # "openfisca-france (>=113.0.2)"
        deps_and_version[package_name] = package_version

    for v in resp["releases"][version]:
        if v["packagetype"] == "sdist":  # for .tag.gz
            return {
                "last_version": version,
                "url": v["url"],
                "sha256": v["digests"]["sha256"],
                "deps_and_version": deps_and_version,
                }
    return {}


def replace_in_file(filepath: str, info: dict):
    """Replace placeholder in meta.yaml by their values.

    ::filepath:: Path to meta.yaml, with filename.
    ::info:: Dict with information to populate.
    """
    with open(filepath, "rt", encoding="utf-8") as fin:
        meta = fin.read()
    # Replace with info from PyPi
    meta = meta.replace("PYPI_VERSION", info["last_version"])
    meta = meta.replace("PYPI_URL", info["url"])
    meta = meta.replace("PYPI_SHA256", info["sha256"])
    with open(filepath, "wt", encoding="utf-8") as fout:
        fout.write(meta)
    print(f"File {filepath} has been updated with info from PyPi.")  # noqa: T001


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-p",
        "--package",
        type=str,
        default="",
        required=True,
        help="The name of the package",
        )
    parser.add_argument(
        "-f",
        "--filename",
        type=str,
        default=".conda/meta.yaml",
        help="Path to meta.yaml, with filename",
        )
    args = parser.parse_args()
    info = get_info(args.package)
    print("Information of the last published PyPi package :", info["last_version"])  # noqa: T001
    replace_in_file(args.filename, info)

@@ -260,26 +260,16 @@
 argparse
-%0Aimport re
 %0A%0Aimport
@@ -894,33 +894,8 @@
 n%22%5D%0A
-    deps_and_version = %7B%7D
 %0A   
@@ -899,23 +899,17 @@
     for 
-package
+v
  in resp
@@ -914,546 +914,94 @@
 sp%5B%22
-info%22%5D%5B%22requires_dist%22%5D:%0A        if %22; extra ==%22 in package:%0A            continue%0A        package_name = package.split(%22(%22)%5B0%5D.replace(%22 %22, %22%22)%0A        package_name = package_name.replace(%22%5Bpipeline%5D%22, %22%22)%0A        if package_name == %22tables%22:%0A            package_name = %22pytables%22%0A        package_version = (%0A            re.search(%22%5C((%5B%5E)%5D+)%22, package).group(1).replace(%22 %22, %22%22)  # noqa: W605%0A            )  # %22openfisca-france (%3E=113.0.2)%22%0A        deps_and_version%5Bpackage_name%5D = package_version%0A%0A    for v in resp%5B%22releases%22%5D%5Bversion%5D:
+releases%22%5D%5Bversion%5D:%0A        # Find packagetype==%22sdist%22 to get source code in .tar.gz
 %0A   
@@ -1040,23 +1040,8 @@
 st%22:
-  # for .tag.gz
 %0A   
@@ -1186,62 +1186,8 @@
 %22%5D,%0A
-                %22deps_and_version%22: deps_and_version,%0A
     

Remove dependancies extraction code