# python library used to update plugins:
# - pkgs/applications/editors/vim/plugins/update.py
# - pkgs/applications/editors/kakoune/plugins/update.py
# - pkgs/development/lua-modules/updater/updater.py

import argparse
import csv
import functools
import http
import json
import logging
import os
import re
import subprocess
import sys
import time
import traceback
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
from dataclasses import asdict, dataclass, replace
from datetime import datetime, date
from functools import wraps
from multiprocessing.dummy import Pool
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Any, Callable
from urllib.parse import unquote, urljoin, urlparse, urlsplit

import git
from packaging.version import InvalidVersion, parse as parse_version

ATOM_ENTRY = "{http://www.w3.org/2005/Atom}entry"  # " vim gets confused here
ATOM_LINK = "{http://www.w3.org/2005/Atom}link"  # "
ATOM_UPDATED = "{http://www.w3.org/2005/Atom}updated"  # "

GIT_TAGS_PREFIX = "refs/tags/"
AUTO_BRANCH = ""

VERSION_DATE_PATTERN = re.compile(r"(\d{4}-\d{2}-\d{2})$")
VERSION_TAG_PATTERN = re.compile(r"^(.+?)-unstable-")
NON_RELEASE_TAG_PREFIXES = ("pre-",)
RELEASE_VERSION_PATTERN = re.compile(r"^[^\d]*(\d[\w.@+-]*)$")

LOG_LEVELS = {
    logging.getLevelName(level): level
    for level in [logging.DEBUG, logging.INFO, logging.WARN, logging.ERROR]
}

log = logging.getLogger()


def retry(ExceptionToCheck: Any, tries: int = 4, delay: float = 3, backoff: float = 2):
    """Retry calling the decorated function using an exponential backoff.
    http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
    original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
    (BSD licensed)
    :param ExceptionToCheck: the exception on which to retry
    :param tries: number of times to try (not retry) before giving up
    :param delay: initial delay between retries in seconds
    :param backoff: backoff multiplier e.g. value of 2 will double the delay
        each retry
    """

    def deco_retry(f: Callable) -> Callable:
        @wraps(f)
        def f_retry(*args: Any, **kwargs: Any) -> Any:
            mtries, mdelay = tries, delay
            while mtries > 1:
                try:
                    return f(*args, **kwargs)
                except ExceptionToCheck as e:
                    print(f"{str(e)}, Retrying in {mdelay} seconds...")
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            return f(*args, **kwargs)

        return f_retry  # true decorator

    return deco_retry


@dataclass
class FetchConfig:
    proc: int
    github_token: str


def make_request(url: str, token=None) -> urllib.request.Request:
    headers = {}
    if token:
        headers["Authorization"] = f"token {token}"
    return urllib.request.Request(url, headers=headers)


# a dictionary of plugins and their new repositories
Redirects = dict["PluginDesc", "Repo"]


def select_latest_tag(
    tags: list[str],
    normalize: Callable[[str], str | None] | None = None,
) -> str | None:
    best_version: tuple[str, Any] | None = None
    best_text: tuple[str, str] | None = None

    for tag in tags:
        candidate = tag if normalize is None else normalize(tag)
        if candidate is None:
            continue

        try:
            version = parse_version(candidate)
            if best_version is None or version > best_version[1]:
                best_version = (tag, version)
        except InvalidVersion:
            if best_text is None or candidate > best_text[1]:
                best_text = (tag, candidate)

    if best_version is not None:
        return best_version[0]
    if best_text is not None:
        return best_text[0]
    return None


def first_release_tag(tags: list[str]) -> str | None:
    for tag in tags:
        normalized_tag = normalize_release_version(tag)
        if normalized_tag is None:
            continue

        try:
            version = parse_version(normalized_tag)
            if version.is_prerelease or version.is_devrelease:
                continue
        except InvalidVersion:
            pass

        return tag

    return None


def tag_from_github_atom_href(href: str) -> str | None:
    path = urlparse(href).path
    marker = "/releases/tag/"
    if marker in path:
        return unquote(path.split(marker, 1)[1])

    tag_name = Path(path).name
    return unquote(tag_name) if tag_name else None


class Repo:
    def __init__(self, uri: str, branch: str) -> None:
        self.uri = uri
        """Url to the repo"""
        self._branch = branch
        # Redirect is the new Repo to use
        self.redirect: "Repo | None" = None
        self.token: str | None = None

    @property
    def name(self):
        return self.uri.strip("/").split("/")[-1]

    @property
    def branch(self):
        return self._branch or "HEAD"

    def __str__(self) -> str:
        return f"{self.uri}"

    def __repr__(self) -> str:
        return f"Repo({self.name}, {self.uri})"

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def has_submodules(self) -> bool:
        return True

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def latest_commit(self) -> tuple[str, datetime]:
        log.debug("Latest commit")
        loaded = self._prefetch(None, fetch_submodules=False)
        updated = datetime.strptime(loaded["date"], "%Y-%m-%dT%H:%M:%S%z")

        return loaded["rev"], updated

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def resolve_ref(self, ref: str) -> tuple[str, datetime]:
        loaded = self._prefetch(ref, fetch_submodules=False)
        updated = datetime.strptime(loaded["date"], "%Y-%m-%dT%H:%M:%S%z")
        return loaded["rev"], updated

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def get_latest_tag(self) -> str | None:
        try:
            # FIXME: This fetches all tags. We need to find a way to check if a tag exists in
            # an ancestor of the default branch.
            cmd = ["git", "ls-remote", "--tags", "--refs", self.uri]
            log.debug("Fetching tags with: %s", cmd)
            output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, timeout=10)
            lines = output.decode("utf-8").strip().split("\n")

            if not lines or lines[0] == "":
                log.debug("No tags found for %s", self.uri)
                return None

            tags = []
            for line in lines:
                if "\t" in line:
                    tag_ref = line.split("\t")[1]
                    if tag_ref.startswith(GIT_TAGS_PREFIX):
                        tag_name = tag_ref[len(GIT_TAGS_PREFIX) :]
                        tags.append(tag_name)

            if not tags:
                return None

            latest_tag = select_latest_tag(tags, normalize_release_version)
            if latest_tag is None:
                latest_tag = select_latest_tag(tags)
            if latest_tag is None:
                log.debug("No tags found for %s", self.uri)
                return None

            log.debug("Found latest tag: %s", latest_tag)
            return latest_tag
        except subprocess.CalledProcessError as e:
            log.debug("Failed to fetch tags for %s: %s", self.uri, e)
            return None
        except Exception as e:
            log.warning("Unexpected error fetching tags for %s: %s", self.uri, e)
            return None

    def _prefetch(self, ref: str | None, fetch_submodules: bool = True):
        cmd = ["nix-prefetch-git", "--quiet"]
        if fetch_submodules:
            cmd.append("--fetch-submodules")
        cmd.append(self.uri)
        if ref is not None:
            cmd.append(ref)
        log.debug(cmd)
        data = subprocess.check_output(cmd)
        loaded = json.loads(data)
        return loaded

    def prefetch(self, ref: str, has_submodules: bool | None = None) -> str:
        log.info("Prefetching %s", self.uri)
        loaded = self._prefetch(ref)
        return loaded["sha256"]

    def as_nix(self, plugin: "Plugin") -> str:
        ref_attr = (
            f'tag = "{plugin.tag}";'
            if plugin.tag is not None
            else f'rev = "{plugin.commit}";'
        )
        return f"""fetchgit {{
      url = "{self.uri}";
      {ref_attr}
      hash = "{plugin.to_sri_hash()}";
    }}"""

    def get_license_spdx_id(self, fallback_license: str | None = None) -> str | None:
        return fallback_license


class RepoGitHub(Repo):
    def __init__(self, owner: str, repo: str, branch: str) -> None:
        self.owner = owner
        self.repo = repo
        self.token = None
        """Url to the repo"""
        super().__init__(self.url(""), branch)
        log.debug(
            "Instantiating github repo owner=%s and repo=%s", self.owner, self.repo
        )

    @property
    def name(self):
        return self.repo

    def url(self, path: str) -> str:
        res = urljoin(f"https://github.com/{self.owner}/{self.repo}/", path)
        return res

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def has_submodules(self) -> bool:
        try:
            req = make_request(self.url(f"blob/{self.branch}/.gitmodules"), self.token)
            urllib.request.urlopen(req, timeout=10).close()
        except urllib.error.HTTPError as e:
            if e.code == 404:
                return False
            else:
                raise
        return True

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def latest_commit(self) -> tuple[str, datetime]:
        commit_url = self.url(f"commits/{self.branch}.atom")
        log.debug("Sending request to %s", commit_url)
        commit_req = make_request(commit_url, self.token)
        with urllib.request.urlopen(commit_req, timeout=10) as req:
            self._check_for_redirect(commit_url, req)
            xml = req.read()

            # Filter out illegal XML characters
            illegal_xml_regex = re.compile(b"[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]")
            xml = illegal_xml_regex.sub(b"", xml)

            root = ET.fromstring(xml)
            latest_entry = root.find(ATOM_ENTRY)
            assert latest_entry is not None, f"No commits found in repository {self}"
            commit_link = latest_entry.find(ATOM_LINK)
            assert commit_link is not None, f"No link tag found feed entry {xml!r}"
            url = urlparse(commit_link.get("href"))
            updated_tag = latest_entry.find(ATOM_UPDATED)
            assert updated_tag is not None and updated_tag.text is not None, (
                f"No updated tag found feed entry {xml!r}"
            )
            updated = datetime.strptime(updated_tag.text, "%Y-%m-%dT%H:%M:%SZ")
            return Path(str(url.path)).name, updated

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def resolve_ref(self, ref: str) -> tuple[str, datetime]:
        if ref == self.branch:
            return self.latest_commit()
        self._check_ref_redirect(ref)
        return super().resolve_ref(ref)

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def _check_ref_redirect(self, ref: str) -> None:
        ref_url = self.url(f"tree/{urllib.parse.quote(ref, safe='')}")
        ref_req = make_request(ref_url, self.token)
        with urllib.request.urlopen(ref_req, timeout=10) as req:
            self._check_for_redirect(ref_url, req)

    def _execute_graphql(self, query: str, variables: dict) -> dict:
        graphql_url = "https://api.github.com/graphql"

        payload = json.dumps({"query": query, "variables": variables}).encode("utf-8")

        req = make_request(graphql_url, self.token)
        req.add_header("Content-Type", "application/json")
        req.data = payload

        with urllib.request.urlopen(req, timeout=10) as response:
            return json.load(response)

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def _get_recent_tags_from_atom(self) -> list[str]:
        tags_url = self.url("tags.atom")
        tags_req = make_request(tags_url, self.token)
        with urllib.request.urlopen(tags_req, timeout=10) as response:
            xml = response.read()

        root = ET.fromstring(xml)
        tags = []
        for entry in root.findall(ATOM_ENTRY):
            link = entry.find(ATOM_LINK)
            if link is None:
                continue

            href = link.get("href")
            if not href:
                continue

            tag_name = tag_from_github_atom_href(href)
            if tag_name:
                tags.append(tag_name)

        return tags

    def _get_latest_tag_from_fallbacks(self) -> str | None:
        try:
            recent_tags = self._get_recent_tags_from_atom()
            if recent_tags:
                latest_tag = first_release_tag(recent_tags)
                return latest_tag if latest_tag is not None else recent_tags[0]
        except (urllib.error.URLError, ET.ParseError) as e:
            log.warning(
                "Failed to fetch GitHub tag feed for %s/%s: %s",
                self.owner,
                self.repo,
                e,
            )

        return super().get_latest_tag()

    @retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
    def get_latest_tag(self) -> str | None:
        try:
            if not self.token or self.token == "":
                return self._get_latest_tag_from_fallbacks()

            query = """
            query GetRecentTags($owner: String!, $name: String!) {
              repository(owner: $owner, name: $name) {
                refs(refPrefix: "refs/tags/", first: 20, orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) {
                  nodes {
                    name
                  }
                }
              }
            }
            """

            data = self._execute_graphql(
                query, {"owner": self.owner, "name": self.repo}
            )

            if "errors" in data:
                if any(
                    error.get("code") == "graphql_rate_limit"
                    or error.get("type") == "RATE_LIMIT"
                    for error in data["errors"]
                ):
                    log.warning(
                        "GitHub GraphQL rate limit hit for %s/%s, falling back to tag feeds",
                        self.owner,
                        self.repo,
                    )
                    return self._get_latest_tag_from_fallbacks()
                log.warning(
                    "GraphQL errors for %s/%s: %s",
                    self.owner,
                    self.repo,
                    data["errors"],
                )
                return self._get_latest_tag_from_fallbacks()

            repo = data.get("data", {}).get("repository")
            if not repo:
                return self._get_latest_tag_from_fallbacks()

            recent_tags = [node["name"] for node in repo["refs"]["nodes"]]
            if not recent_tags:
                return self._get_latest_tag_from_fallbacks()

            latest_tag = first_release_tag(recent_tags)
            return latest_tag if latest_tag is not None else recent_tags[0]

        except urllib.error.HTTPError as e:
            if e.code in (401, 403):
                raise RuntimeError(
                    "GitHub GraphQL auth failed for "
                    f"{self.owner}/{self.repo} ({e.code}); refresh GITHUB_TOKEN"
                ) from e
            raise
        except Exception as e:
            log.warning(
                "Error fetching version info for %s/%s: %s",
                self.owner,
                self.repo,
                e,
                exc_info=True,
            )
            return self._get_latest_tag_from_fallbacks()

    def _check_for_redirect(self, url: str, req: http.client.HTTPResponse):
        response_url = req.geturl()
        if url != response_url:
            new_owner, new_name = urlsplit(response_url).path.strip("/").split("/")[:2]

            new_repo = RepoGitHub(owner=new_owner, repo=new_name, branch=self._branch)
            self.redirect = new_repo

    def prefetch(self, commit: str, has_submodules: bool | None = None) -> str:
        if has_submodules is None:
            has_submodules = self.has_submodules()

        if has_submodules:
            sha256 = super().prefetch(commit)
        else:
            sha256 = self.prefetch_github(commit)
        return sha256

    def prefetch_github(self, ref: str) -> str:
        cmd = ["nix-prefetch-github", self.owner, self.repo, "--rev", ref, "--json"]
        log.debug("Running %s", cmd)
        data = subprocess.check_output(cmd)
        loaded = json.loads(data)
        return loaded["hash"]

    def get_license_spdx_id(self, fallback_license: str | None = None) -> str | None:
        license_url = f"https://api.github.com/repos/{self.owner}/{self.repo}/license"
        log.debug("Fetching license metadata from %s", license_url)

        def log_fetch_failure(reason: str) -> str | None:
            log.warning(
                "Failed to fetch license metadata for %s/%s: %s; reusing %s",
                self.owner,
                self.repo,
                reason,
                fallback_license or "no cached license",
            )
            return fallback_license

        try:
            req = make_request(license_url, self.token)
            with urllib.request.urlopen(req, timeout=10) as response:
                data = json.load(response)
        except urllib.error.HTTPError as e:
            if e.code == 404:
                return None
            return log_fetch_failure(f"HTTP {e.code}")
        except urllib.error.URLError as e:
            return log_fetch_failure(str(e))

        license_info = data.get("license")
        if not isinstance(license_info, dict):
            return None

        spdx_id = license_info.get("spdx_id")
        if not spdx_id or spdx_id == "NOASSERTION":
            return None

        return spdx_id

    def as_nix(self, plugin: "Plugin") -> str:
        if plugin.has_submodules:
            submodule_attr = "\n      fetchSubmodules = true;"
        else:
            submodule_attr = ""

        ref_attr = (
            f'tag = "{plugin.tag}";'
            if plugin.tag is not None
            else f'rev = "{plugin.commit}";'
        )

        return f"""fetchFromGitHub {{
      owner = "{self.owner}";
      repo = "{self.repo}";
      {ref_attr}
      hash = "{plugin.to_sri_hash()}";{submodule_attr}
    }}"""


@dataclass(frozen=True)
class PluginDesc:
    repo: Repo
    branch: str
    alias: str | None

    @property
    def name(self):
        return self.alias or self.repo.name

    @staticmethod
    def load_from_csv(config: FetchConfig, row: dict[str, str]) -> "PluginDesc":
        log.debug("Loading row %s", row)
        branch = row["branch"]
        repo = make_repo(row["repo"], branch.strip())
        repo.token = config.github_token
        return PluginDesc(
            repo,
            branch.strip(),
            # alias is usually an empty string
            row["alias"] if row["alias"] else None,
        )

    @staticmethod
    def load_from_string(config: FetchConfig, line: str) -> "PluginDesc":
        branch = AUTO_BRANCH
        alias = None
        uri = line
        if " as " in uri:
            uri, alias = uri.split(" as ")
            alias = alias.strip()
        if "@" in uri:
            uri, branch = uri.split("@")
        repo = make_repo(uri.strip(), branch.strip())
        repo.token = config.github_token
        return PluginDesc(repo, branch.strip(), alias)


@dataclass
class Plugin:
    name: str
    commit: str
    has_submodules: bool
    sha256: str
    version: str
    date: datetime | None = None
    last_tag: str | None = None
    tag: str | None = None
    license: str | None = None

    @property
    def normalized_name(self) -> str:
        return self.name.replace(".", "-")

    def to_sri_hash(self) -> str:
        if self.sha256.startswith("sha256-"):
            return self.sha256

        cmd = [
            "nix",
            "hash",
            "convert",
            "--hash-algo",
            "sha256",
            "--to",
            "sri",
            self.sha256,
        ]
        result = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
        return result.decode("utf-8").strip()

    @staticmethod
    def parse_version_string(version_str: str) -> tuple[datetime, str | None]:
        date_match = VERSION_DATE_PATTERN.search(version_str)
        if not date_match:
            raise ValueError(f"Cannot parse unstable version: {version_str}")
        date = datetime.fromisoformat(date_match.group(1))

        tag_match = VERSION_TAG_PATTERN.search(version_str)
        last_tag = (
            tag_match.group(1) if tag_match and tag_match.group(1) != "0" else None
        )

        return date, last_tag

    def as_json(self) -> dict[str, str]:
        copy = self.__dict__.copy()
        del copy["date"]
        return copy


def normalize_release_version(tag: str) -> str | None:
    normalized_tag = tag.strip()
    lowered_tag = normalized_tag.lower()
    if any(lowered_tag.startswith(prefix) for prefix in NON_RELEASE_TAG_PREFIXES):
        return None

    match = RELEASE_VERSION_PATTERN.match(normalized_tag)
    if match is not None:
        return match.group(1)

    return None


def make_unstable_version(date: datetime, last_tag: str | None) -> str:
    date_str = date.strftime("%Y-%m-%d")

    tag_part = "0"
    if last_tag:
        normalized_tag = normalize_release_version(last_tag)
        if normalized_tag is not None:
            tag_part = normalized_tag

    return f"{tag_part}-unstable-{date_str}"


def newer_version_tag(first_tag: str | None, second_tag: str | None) -> str | None:
    if first_tag is None:
        return second_tag
    if second_tag is None:
        return first_tag

    first_version = normalize_release_version(first_tag)
    second_version = normalize_release_version(second_tag)
    if first_version is None:
        return second_tag
    if second_version is None:
        return first_tag

    try:
        return (
            first_tag
            if parse_version(first_version) >= parse_version(second_version)
            else second_tag
        )
    except InvalidVersion:
        return first_tag if first_version >= second_version else second_tag


def get_commit_target(
    repo: Repo,
    branch: str,
    latest_tag: str | None,
) -> tuple[str, datetime, str, str | None]:
    if branch == "HEAD":
        commit, date = repo.latest_commit()
    else:
        commit, date = repo.resolve_ref(branch)

    return commit, date, make_unstable_version(date, latest_tag), None


def select_plugin_target(
    plugin_desc: PluginDesc,
    current_plugin: Plugin | None,
    latest_tag: str | None,
) -> tuple[str, datetime, str, str | None]:
    branch = plugin_desc.branch

    if branch != AUTO_BRANCH:
        return get_commit_target(plugin_desc.repo, branch, latest_tag)

    release_version = (
        normalize_release_version(latest_tag) if latest_tag is not None else None
    )
    if release_version is None:
        return get_commit_target(plugin_desc.repo, "HEAD", latest_tag)

    release_commit, release_date = plugin_desc.repo.resolve_ref(
        f"{GIT_TAGS_PREFIX}{latest_tag}"
    )

    if current_plugin is not None:
        if (
            current_plugin.date is not None
            and current_plugin.tag is None
            and current_plugin.date.date() > release_date.date()
        ):
            latest_tag = newer_version_tag(current_plugin.last_tag, latest_tag)
            return get_commit_target(plugin_desc.repo, "HEAD", latest_tag)

    return release_commit, release_date, release_version, latest_tag


def load_plugins_from_csv(
    config: FetchConfig,
    input_file: Path,
) -> list[PluginDesc]:
    log.debug("Load plugins from csv %s", input_file)
    plugins = []
    with open(input_file, newline="") as csvfile:
        log.debug("Writing into %s", input_file)
        reader = csv.DictReader(
            csvfile,
        )
        for line in reader:
            plugin = PluginDesc.load_from_csv(config, line)
            plugins.append(plugin)

    return plugins


def run_nix_expr(expr, nixpkgs: str, **args):
    """
    :param expr nix expression to fetch current plugins
    :param nixpkgs Path towards a nixpkgs checkout
    """
    with CleanEnvironment(nixpkgs) as nix_path:
        cmd = [
            "nix",
            "eval",
            "--extra-experimental-features",
            "nix-command",
            "--impure",
            "--json",
            "--expr",
            expr,
            "--nix-path",
            nix_path,
        ]
        log.debug("Running command: %s", " ".join(cmd))
        out = subprocess.check_output(cmd, **args)
        data = json.loads(out)
        return data


class Editor:
    """The configuration of the update script."""

    def __init__(
        self,
        name: str,
        root: Path,
        get_plugins: str,
        default_in: Path | None = None,
        default_out: Path | None = None,
        deprecated: Path | None = None,
        cache_file: str | None = None,
    ):
        log.debug("get_plugins:", get_plugins)
        self.name = name
        self.root = root
        self.get_plugins = get_plugins
        self.default_in = default_in or root.joinpath(f"{name}-plugin-names")
        self.default_out = default_out or root.joinpath("generated.nix")
        self.deprecated = deprecated or root.joinpath("deprecated.json")
        self.cache_file = cache_file or f"{name}-plugin-cache.json"
        self.nixpkgs_repo: git.Repo | None = None

    def add(self, args):
        """CSV spec"""
        log.debug("called the 'add' command")
        fetch_config = FetchConfig(args.proc, args.github_token)
        editor = self
        for plugin_line in args.add_plugins:
            log.debug("using plugin_line %s", plugin_line)
            pdesc = PluginDesc.load_from_string(fetch_config, plugin_line)
            log.debug("loaded as pdesc %s", pdesc)
            append = [pdesc]
            editor.rewrite_input(
                fetch_config, args.input_file, editor.deprecated, append=append
            )
            plugin, _ = prefetch_plugin(pdesc)

            if (  # lua updater doesn't support updating individual plugin
                self.name != "lua"
            ):
                # update generated.nix
                update = self.get_update(
                    args.input_file,
                    args.outfile,
                    fetch_config,
                    [plugin.normalized_name],
                )
                update()

            autocommit = not args.no_commit
            if autocommit:
                assert editor.nixpkgs_repo is not None

                commit_message = "{drv_name}: init at {version}".format(
                    drv_name=editor.get_drv_name(plugin.normalized_name),
                    version=plugin.version,
                )

                if isinstance(pdesc.repo, RepoGitHub):
                    github_url = (
                        f"https://github.com/{pdesc.repo.owner}/{pdesc.repo.repo}"
                    )
                    commit_message += f"\n\n{github_url}"

                commit(
                    editor.nixpkgs_repo,
                    commit_message,
                    [args.outfile, args.input_file],
                )

    # Expects arguments generated by 'update' subparser
    def update(self, args):
        """CSV spec"""
        print("the update member function should be overridden in subclasses")

    def get_current_plugins(
        self, config: FetchConfig, nixpkgs: str
    ) -> list[tuple[PluginDesc, Plugin]]:
        """To fill the cache"""
        data = run_nix_expr(self.get_plugins, nixpkgs)
        plugins = []
        for name, attr in data.items():
            checksum = attr["checksum"]
            version_str = attr["version"]
            source_tag = checksum.get("tag")

            if source_tag is not None:
                date, last_tag = None, None
            else:
                date, last_tag = Plugin.parse_version_string(version_str)

            pdesc = PluginDesc.load_from_string(config, f"{attr['homePage']} as {name}")
            p = Plugin(
                attr["pname"],
                checksum["rev"],
                checksum["submodules"],
                checksum["sha256"],
                version_str,
                date,
                last_tag=last_tag,
                tag=source_tag,
                license=attr.get("license"),
            )

            plugins.append((pdesc, p))
        return plugins

    def load_plugin_spec(self, config: FetchConfig, plugin_file) -> list[PluginDesc]:
        """CSV spec"""
        return load_plugins_from_csv(config, plugin_file)

    def generate_nix(self, _plugins, _outfile: str):
        """Returns nothing for now, writes directly to outfile"""
        raise NotImplementedError()

    def filter_plugins_to_update(
        self, plugin: PluginDesc, to_update: list[str]
    ) -> bool:
        """Function for filtering out plugins, that user doesn't want to update.

        It is mainly used for updating only specific plugins, not all of them.
        By default it filters out plugins not present in `to_update`,
        assuming `to_update` is a list of plugin names (the same as in the
        result expression).

        This function is never called if `to_update` is empty.
        Feel free to override this function in derived classes.

        Note:
            Known bug: you have to use a deprecated name, instead of new one.
            This is because we resolve deprecations later and can't get new
            plugin URL before we request info about it.

            Although, we could parse deprecated.json, but it's a whole bunch
            of spaghetti code, which I don't want to write.

        Arguments:
            plugin: Plugin on which you decide whether to ignore or not.
            to_update:
                List of strings passed to via the `--update` command line parameter.
                By default, we assume it is a list of URIs identical to what
                is in the input file.

        Returns:
            True if we should update plugin and False if not.
        """
        return plugin.name.replace(".", "-") in to_update

    def get_update(
        self,
        input_file: str,
        output_file: str,
        config: FetchConfig,
        to_update: list[str] | None,
    ):
        if to_update is None:
            to_update = []

        current_plugins = self.get_current_plugins(config, self.nixpkgs)
        current_plugin_specs = self.load_plugin_spec(config, input_file)

        cache: Cache = Cache(current_plugins, self.cache_file)
        current_plugin_map = {
            plugin.normalized_name: plugin for _description, plugin in current_plugins
        }
        _prefetch = functools.partial(
            prefetch,
            cache=cache,
            current_plugins=current_plugin_map,
        )

        to_update_for_filter = [x.replace(".", "-") for x in to_update]
        plugins_to_update = (
            current_plugin_specs
            if len(to_update) == 0
            else [
                description
                for description in current_plugin_specs
                if self.filter_plugins_to_update(description, to_update_for_filter)
            ]
        )

        def update() -> tuple[Redirects, list[tuple[str, str, str]]]:
            """
            Returns:
                tuple of (redirects, updated_plugins)
                where updated_plugins is [(name, old_version, new_version), ...]
            """
            if len(plugins_to_update) == 0:
                log.error(
                    "\n\n\n\nIt seems like you provided some arguments to `--update`:\n"
                    + ", ".join(to_update)
                    + "\nBut after filtering, the result list of plugins is empty\n"
                    "\n"
                    "Are you sure you provided the same URIs as in your input file?\n"
                    "(" + str(input_file) + ")\n\n"
                )
                return {}, []

            try:
                pool = Pool(processes=config.proc)
                results = pool.map(_prefetch, plugins_to_update)
            finally:
                cache.store()

            print(f"{len(results)} of {len(current_plugins)} were checked")
            results = self.merge_results(current_plugins, results)
            plugins, redirects = check_results(results)

            # Track version changes for commit message generation
            updated_plugins = []
            for _, new_plugin in plugins:
                old_plugin = current_plugin_map.get(new_plugin.normalized_name)
                if old_plugin and old_plugin.version != new_plugin.version:
                    updated_plugins.append(
                        (
                            new_plugin.normalized_name,
                            old_plugin.version,
                            new_plugin.version,
                        )
                    )

            plugins = sorted(plugins, key=lambda v: v[1].normalized_name)
            self.generate_nix(plugins, output_file)

            return redirects, updated_plugins

        return update

    def merge_results(
        self,
        current: list[tuple[PluginDesc, Plugin]],
        fetched: list[tuple[PluginDesc, Exception | Plugin, Repo | None]],
    ) -> list[tuple[PluginDesc, Exception | Plugin, Repo | None]]:
        # transforming this to dict, so lookup is O(1) instead of O(n) (n is len(current))
        result: dict[str, tuple[PluginDesc, Exception | Plugin, Repo | None]] = {
            # also adding redirect (third item in the result tuple)
            pl.normalized_name: (pdesc, pl, None)
            for pdesc, pl in current
        }

        for plugin_desc, plugin, redirect in fetched:
            # Check if plugin is a Plugin object and has normalized_name attribute
            if isinstance(plugin, Plugin) and hasattr(plugin, "normalized_name"):
                result[plugin.normalized_name] = (plugin_desc, plugin, redirect)
            elif isinstance(plugin, Exception):
                log.warning(
                    "Keeping current plugin data after error fetching %s: %r",
                    plugin_desc.name,
                    plugin,
                )
            else:
                # For unexpected types, log the issue
                log.error(
                    f"Unexpected plugin type for {plugin_desc.name}: {type(plugin)}"
                )

        return list(result.values())

    @property
    def attr_path(self):
        return self.name + "Plugins"

    def get_drv_name(self, name: str):
        return self.attr_path + "." + name

    def rewrite_input(self, *args, **kwargs):
        return rewrite_input(*args, **kwargs)

    def create_parser(self):
        common = argparse.ArgumentParser(
            add_help=False,
            description=(
                f"""
                Updates nix derivations for {self.name} plugins.\n
                By default from {self.default_in} to {self.default_out}"""
            ),
        )
        common.add_argument(
            "--nixpkgs",
            type=str,
            default=os.getcwd(),
            help="Adjust log level",
        )
        common.add_argument(
            "--input-names",
            "-i",
            dest="input_file",
            type=Path,
            default=self.default_in,
            help="A list of plugins in the form owner/repo",
        )
        common.add_argument(
            "--out",
            "-o",
            dest="outfile",
            default=self.default_out,
            type=Path,
            help="Filename to save generated nix code",
        )
        common.add_argument(
            "--proc",
            "-p",
            dest="proc",
            type=int,
            default=30,
            help="Number of concurrent processes to spawn. Setting --github-token allows higher values.",
        )
        common.add_argument(
            "--github-token",
            "-t",
            type=str,
            default=os.getenv("GITHUB_TOKEN"),
            help="""Allows to set --proc to higher values.
            Uses GITHUB_TOKEN environment variables as the default value.""",
        )
        common.add_argument(
            "--no-commit",
            "-n",
            action="store_true",
            default=False,
            help="Whether to autocommit changes",
        )
        common.add_argument(
            "--debug",
            "-d",
            choices=LOG_LEVELS.keys(),
            default=logging.getLevelName(logging.WARN),
            help="Adjust log level",
        )

        main = argparse.ArgumentParser(
            parents=[common],
            description=(
                f"""
                Updates nix derivations for {self.name} plugins.\n
                By default from {self.default_in} to {self.default_out}"""
            ),
        )

        subparsers = main.add_subparsers(dest="command", required=False)
        padd = subparsers.add_parser(
            "add",
            parents=[],
            description="Add new plugin",
            add_help=False,
        )
        padd.set_defaults(func=self.add)
        padd.add_argument(
            "add_plugins",
            default=None,
            nargs="+",
            help=f"Plugin to add to {self.attr_path} from Github in the form owner/repo",
        )

        pupdate = subparsers.add_parser(
            "update",
            description="Update all or a subset of existing plugins",
            add_help=False,
        )
        pupdate.add_argument(
            "update_only",
            default=None,
            nargs="*",
            help="Plugin URLs to update (must be the same as in the input file)",
        )
        pupdate.set_defaults(func=self.update)
        return main

    def run(
        self,
    ):
        """
        Convenience function
        """
        parser = self.create_parser()
        args = parser.parse_args()
        command = args.command or "update"
        logging.basicConfig()
        log.setLevel(LOG_LEVELS[args.debug])
        log.info("Chose to run command: %s", command)
        self.nixpkgs = args.nixpkgs

        self.nixpkgs_repo = git.Repo(args.nixpkgs, search_parent_directories=True)

        getattr(self, command)(args)


class CleanEnvironment(object):
    def __init__(self, nixpkgs):
        self.local_pkgs = nixpkgs

    def __enter__(self) -> str:
        """
        local_pkgs = str(Path(__file__).parent.parent.parent)
        """
        self.old_environ = os.environ.copy()
        self.empty_config = NamedTemporaryFile()
        self.empty_config.write(b"{}")
        self.empty_config.flush()
        return f"localpkgs={self.local_pkgs}"

    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
        os.environ.update(self.old_environ)
        self.empty_config.close()


def prefetch_plugin(
    p: PluginDesc,
    cache: "Cache | None" = None,
    current_plugin: Plugin | None = None,
) -> tuple[Plugin, Repo | None]:
    log.info(f"Fetching source for plugin {p.name} from {p.repo.uri}@{p.branch}")

    latest_tag = p.repo.get_latest_tag()
    if latest_tag:
        log.debug("Latest tag for %s: %s", p.name, latest_tag)
    else:
        log.debug("No tags found for %s, will use '0' prefix", p.name)

    commit, date, version, source_tag = select_plugin_target(
        p,
        current_plugin,
        latest_tag,
    )

    cached_plugin = (
        cache[target_cache_key(p.repo.uri, commit, source_tag)] if cache else None
    )
    if cached_plugin is not None:
        log.debug(f"Cache hit for {p.name}!")
        license_spdx_id = (
            cached_plugin.license
            or (current_plugin.license if current_plugin else None)
            or p.repo.get_license_spdx_id()
        )
        return (
            replace(
                cached_plugin,
                name=p.name,
                commit=commit,
                version=version,
                date=date,
                last_tag=latest_tag,
                tag=source_tag,
                license=license_spdx_id,
            ),
            p.repo.redirect,
        )

    has_submodules = p.repo.has_submodules()
    log.debug(f"prefetch {p.name}")
    sha256 = (
        p.repo.prefetch(f"{GIT_TAGS_PREFIX}{source_tag}", has_submodules=has_submodules)
        if source_tag
        else p.repo.prefetch(commit, has_submodules=has_submodules)
    )
    license_spdx_id = (
        current_plugin.license
        if current_plugin and current_plugin.license
        else p.repo.get_license_spdx_id()
    )

    return (
        Plugin(
            p.name,
            commit,
            has_submodules,
            sha256,
            version,
            date=date,
            last_tag=latest_tag,
            tag=source_tag,
            license=license_spdx_id,
        ),
        p.repo.redirect,
    )


def print_download_error(plugin: PluginDesc, ex: Exception):
    print(f"{plugin}: {ex}", file=sys.stderr)
    ex_traceback = ex.__traceback__
    tb_lines = [
        line.rstrip("\n")
        for line in traceback.format_exception(ex.__class__, ex, ex_traceback)
    ]
    print("\n".join(tb_lines))


def check_results(
    results: list[tuple[PluginDesc, Exception | Plugin, Repo | None]],
) -> tuple[list[tuple[PluginDesc, Plugin]], Redirects]:
    """ """
    failures: list[tuple[PluginDesc, Exception]] = []
    plugins = []
    redirects: Redirects = {}
    for pdesc, result, redirect in results:
        if isinstance(result, Exception):
            failures.append((pdesc, result))
        else:
            new_pdesc = pdesc
            if redirect is not None:
                redirects.update({pdesc: redirect})
                new_pdesc = PluginDesc(redirect, pdesc.branch, pdesc.alias)
                result.name = new_pdesc.name
            plugins.append((new_pdesc, result))

    if len(failures) == 0:
        return plugins, redirects
    else:
        log.error(f"{len(failures)} plugin(s) could not be downloaded:\n")

        for plugin, exception in failures:
            print_download_error(plugin, exception)

        sys.exit(1)


def make_repo(uri: str, branch) -> Repo:
    """Instantiate a Repo with the correct specialization depending on server (gitub spec)"""
    # dumb check to see if it's of the form owner/repo (=> github) or https://...
    res = urlparse(uri)
    if res.netloc in ["github.com", ""]:
        owner, repo = res.path.strip("/").split("/")
        return RepoGitHub(owner, repo, branch)
    else:
        return Repo(uri.strip(), branch)


def get_cache_path(cache_file_name: str) -> Path | None:
    xdg_cache = os.environ.get("XDG_CACHE_HOME", None)
    if xdg_cache is None:
        home = os.environ.get("HOME", None)
        if home is None:
            return None
        xdg_cache = str(Path(home, ".cache"))

    return Path(xdg_cache, cache_file_name)


def plugin_cache_key(repo_uri: str, plugin: "Plugin") -> str:
    ref = f"{GIT_TAGS_PREFIX}{plugin.tag}" if plugin.tag is not None else plugin.commit
    return f"{repo_uri}@{ref}"


def target_cache_key(repo_uri: str, commit: str, source_tag: str | None) -> str:
    ref = f"{GIT_TAGS_PREFIX}{source_tag}" if source_tag is not None else commit
    return f"{repo_uri}@{ref}"


class Cache:
    def __init__(
        self,
        initial_plugins: list[tuple[PluginDesc, Plugin]],
        cache_file_name: str,
    ) -> None:
        self.cache_file = get_cache_path(cache_file_name)

        downloads = {}
        for plugin_desc, plugin in initial_plugins:
            downloads[plugin_cache_key(plugin_desc.repo.uri, plugin)] = plugin
        downloads.update(self.load())
        self.downloads = downloads

    def load(self) -> dict[str, Plugin]:
        if self.cache_file is None or not self.cache_file.exists():
            return {}

        downloads: dict[str, Plugin] = {}
        with open(self.cache_file) as f:
            data = json.load(f)
            for cache_key, attr in data.items():
                p = Plugin(
                    attr["name"],
                    attr["commit"],
                    attr["has_submodules"],
                    attr["sha256"],
                    attr.get("version", ""),
                    last_tag=attr.get("last_tag"),
                    tag=attr.get("tag"),
                    license=attr.get("license"),
                )
                downloads[cache_key] = p
        return downloads

    def store(self) -> None:
        if self.cache_file is None:
            return

        os.makedirs(self.cache_file.parent, exist_ok=True)
        with open(self.cache_file, "w+") as f:
            data = {}
            for cache_key, attr in self.downloads.items():
                data[cache_key] = attr.as_json()
            json.dump(data, f, indent=4, sort_keys=True)

    def __getitem__(self, key: str) -> Plugin | None:
        return self.downloads.get(key, None)

    def __setitem__(self, key: str, value: Plugin) -> None:
        self.downloads[key] = value


def prefetch(
    pluginDesc: PluginDesc,
    cache: Cache,
    current_plugins: dict[str, Plugin] | None = None,
) -> tuple[PluginDesc, Exception | Plugin, Repo | None]:
    try:
        current_plugin = None
        if current_plugins is not None:
            current_plugin = current_plugins.get(pluginDesc.name.replace(".", "-"))
        plugin, redirect = prefetch_plugin(pluginDesc, cache, current_plugin)
        cache[target_cache_key(pluginDesc.repo.uri, plugin.commit, plugin.tag)] = plugin
        return (pluginDesc, plugin, redirect)
    except Exception as e:
        return (pluginDesc, e, None)


def rewrite_input(
    config: FetchConfig,
    input_file: Path,
    deprecated: Path,
    # old pluginDesc and the new
    redirects: Redirects = {},
    append: list[PluginDesc] = [],
):
    log.info("Rewriting input file %s", input_file)
    plugins = load_plugins_from_csv(config, input_file)

    plugins.extend(append)

    if redirects:
        log.debug("Dealing with deprecated plugins listed in %s", deprecated)

        cur_date_iso = datetime.now().strftime("%Y-%m-%d")
        with open(deprecated, "r") as f:
            deprecations = json.load(f)
        # TODO parallelize this step
        for pdesc, new_repo in redirects.items():
            log.info("Resolving deprecated plugin %s -> %s", pdesc.name, new_repo.name)
            new_pdesc = PluginDesc(new_repo, pdesc.branch, pdesc.alias)

            old_plugin, _ = prefetch_plugin(pdesc)
            new_plugin, _ = prefetch_plugin(new_pdesc)

            if old_plugin.normalized_name != new_plugin.normalized_name:
                deprecations[old_plugin.normalized_name] = {
                    "new": new_plugin.normalized_name,
                    "date": cur_date_iso,
                }

            # remove plugin from index file, so we won't add it to deprecations again
            for i, plugin in enumerate(plugins):
                if plugin.name == pdesc.name:
                    plugins.pop(i)
                    break
            plugins.append(new_pdesc)

        with open(deprecated, "w") as f:
            json.dump(deprecations, f, indent=4, sort_keys=True)
            f.write("\n")

    with open(input_file, "w") as f:
        log.debug("Writing into %s", input_file)
        # fields = dataclasses.fields(PluginDesc)
        fieldnames = ["repo", "branch", "alias"]
        writer = csv.DictWriter(f, fieldnames, dialect="unix", quoting=csv.QUOTE_NONE)
        writer.writeheader()
        for plugin in sorted(plugins, key=lambda x: x.name):
            writer.writerow(asdict(plugin))


def commit(repo: git.Repo, message: str, files: list[Path]) -> None:
    repo.index.add([str(f.resolve()) for f in files])

    if repo.index.diff("HEAD"):
        print(f'committing to nixpkgs "{message}"')
        repo.index.commit(message)
    else:
        print("no changes in working tree to commit")


def update_plugins(editor: Editor, args):
    """The main entry function of this module.
    All input arguments are grouped in the `Editor`."""

    log.info("Start updating plugins")
    if args.proc > 1 and args.github_token is None:
        log.warning(
            "You have enabled parallel updates but haven't set a github token.\n"
            "You may be hit with `HTTP Error 429: too many requests` as a consequence."
            "Either set --proc=1 or --github-token=YOUR_TOKEN. "
        )

    fetch_config = FetchConfig(args.proc, args.github_token)
    update = editor.get_update(
        input_file=args.input_file,
        output_file=args.outfile,
        config=fetch_config,
        to_update=getattr(  # if script was called without arguments
            args, "update_only", None
        ),
    )

    start_time = time.time()
    redirects, updated_plugins = update()
    duration = time.time() - start_time
    print(f"The plugin update took {duration:.2f}s.")
    editor.rewrite_input(fetch_config, args.input_file, editor.deprecated, redirects)

    autocommit = not args.no_commit

    if autocommit and len(updated_plugins) > 0:
        try:
            repo = git.Repo(os.getcwd())

            if len(updated_plugins) == 1:
                name, old_ver, new_ver = updated_plugins[0]
                message = f"{editor.attr_path}.{name}: {old_ver} -> {new_ver}"
            else:
                message = f"{editor.attr_path}: update on {date.today()}"

            print(args.outfile)
            commit(repo, message, [args.outfile])
        except git.InvalidGitRepositoryError as e:
            print(f"Not in a git repository: {e}", file=sys.stderr)
            sys.exit(1)

    if redirects:
        update()
        if autocommit:
            assert editor.nixpkgs_repo is not None
            commit(
                editor.nixpkgs_repo,
                f"{editor.attr_path}: resolve github repository redirects",
                [args.outfile, args.input_file, editor.deprecated],
            )
