#!/usr/bin/env python3
import configparser
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path
from tempfile import NamedTemporaryFile
from textwrap import dedent
from typing import Dict, Iterable, List, Optional, Set, Tuple
from zipfile import ZipFile

import requests
from git import Repo
from xdg.BaseDirectory import xdg_cache_home, xdg_config_home, xdg_data_home

IOSEVKA_REPO = "https://github.com/be5invis/iosevka"
NERDFONT_PATCHER_ZIP = (
    "https://github.com/ryanoasis/nerd-fonts/releases/latest/download/FontPatcher.zip"
)


def get_repo(repo_dir: Path, remote_url: str) -> Repo:
    if repo_dir.exists():
        print(f"Updating {IOSEVKA_REPO} ...", file=sys.stderr)
        repo = Repo(repo_dir)
        repo.remote().pull()
    else:
        print(f"Cloning {remote_url} ...", file=sys.stderr)
        repo = Repo.clone_from(remote_url, repo_dir, depth=1)
    return repo


def install_iosevka(repo_dir: Path):
    get_repo(repo_dir, IOSEVKA_REPO)

    print("Installing iosevka...", file=sys.stderr)
    try:
        subprocess.run(["npm", "install"], cwd=repo_dir).check_returncode()
        subprocess.run(
            ["npm", "install", "--package-lock-only"],
            cwd=repo_dir,
        ).check_returncode()
        subprocess.run(["npm", "audit", "fix"], cwd=repo_dir).check_returncode()
    except subprocess.CalledProcessError:
        print("Failed to install iosevka", file=sys.stderr)
        sys.exit(1)
    else:
        print("Iosevka installed.", file=sys.stderr)


def generate_font_plan(
    iosevka_dir: Path,
    font_name: str,
    font_styles: Dict[str, Set[str]],
):
    family_name = f"Iosevka {font_name.title()}"
    print(f"Building font with family name: {family_name}")

    with open(iosevka_dir / "private-build-plans.toml", "w") as fp:
        sep = """
            """
        conf = f"""
            [buildPlans.{font_name}]
            family = "{font_name}"
            {sep.join(font_styles["options"])}

            [buildPlans.{font_name}.variants.design]
            {sep.join(font_styles["common"])}

            [buildPlans.{font_name}.variants.upright]
            {sep.join(font_styles["upright"])}

            [buildPlans.{font_name}.variants.italic]
            {sep.join(font_styles["italic"])}

            [buildPlans.{font_name}.variants.oblique]
            {sep.join(font_styles["oblique"])}

            [buildPlans.{font_name}.ligations]
            inherits = "{" ".join(font_styles["ligations"])}"
        """

        print(f"Building iosevka conf:\n{conf}", file=sys.stderr)
        fp.write(dedent(conf))


def generate_font(iosevka_dir: Path, plan_name: str) -> None:
    subprocess.run(
        ["npm", "run", "build", "--", f"ttf::{plan_name}"],
        cwd=iosevka_dir,
    ).check_returncode()


def nerdfont_patch(
    font_dir: Path,
    cache_dir: Path,
    family: str,
    options: Iterable[str] = [],
    mono: bool = True,
) -> None:
    with (
        requests.get(NERDFONT_PATCHER_ZIP, stream=True) as response,
        NamedTemporaryFile(mode="w+b", delete=False) as response_fp,
    ):
        response.raise_for_status()
        for chunk in response.iter_content(chunk_size=8192):
            response_fp.write(chunk)

    with ZipFile(response_fp.name, "r") as zip_fp:
        zip_fp.extractall(cache_dir)

    for font in filter(Path.is_file, font_dir.glob("*")):
        print(f"Patching {font} with nerdfont ...", file=sys.stderr)
        # nerdfont patcher will overwrite the family with --name, which is also the filename;
        # so we name it with the family name, and now move it back to overwrite the original.
        patched_font = (
            font.parent
            / f"{family.replace(' ', '')}-{font.stem.split('-', 1)[1]}{font.suffix}"
        )
        subprocess.run(
            [
                f"{cache_dir}/font-patcher",
                "--careful",
                "--progressbars",
                *(["--mono"] if mono else []),
                f"--name={patched_font.stem}",
                *map(lambda o: f"--{o}", options),
                font,
            ],
            cwd=font_dir,
        ).check_returncode()
        print(f"Replacing {font} with patched {patched_font}", file=sys.stderr)
        patched_font.rename(font)


def parse_config_ini(
    config_file: Path,
) -> Tuple[str, Dict[str, Set[str]], Optional[List]]:
    print(f"Parsing iosevka-generate conf: {config_file} ...", file=sys.stderr)

    config = configparser.ConfigParser(
        allow_no_value=True, inline_comment_prefixes=(";")
    )
    config.read_dict({"options": {"name": "myosevka"}})

    sections = {"common", "upright", "italic", "oblique", "ligations", "options"}
    config.read_dict({s: {} for s in sections})
    config.read(config_file)

    font_styles = {
        section: (
            {f'{char} = "{style}"' for char, style in config[section].items()}
            if section != "options"
            else set()
        )
        for section in sections
    }

    nerdfont: Optional[List] = None
    for option, value in config["options"].items():
        if option == "name":
            font_name = value
        elif option == "nerdfont":
            nerdfont = value.split(" ")
        elif option == "ligset":
            font_styles["ligations"].add(value)
        else:
            font_styles["options"].add(f'{option} = "{value}"')

    return (font_name, font_styles, nerdfont)


def parse_config_toml(
    config_file: Path,
) -> Tuple[Tuple[str, str], Dict[str, Set[str]], Optional[List]]:
    print(f"Parsing iosevka-generate conf: {config_file} ...", file=sys.stderr)

    with open(config_file, "rb") as fp:
        config = tomllib.load(fp)

    names = config["buildPlans"].keys()
    assert len(names) == 1
    name = next(iter(names))

    styles: Dict = {
        "common": [],
    }
    if (sp := config["buildPlans"][name].get("spacing")) in {"fontconfig-mono", "term"}:
        styles["common"].append("sp-term")
    elif sp in {"fixed"}:
        styles["common"].append("sp-fixed")

    opts = config["buildPlans"][name].get("iosevka-generate", {})
    nerdfont = opts.get("nerdfont", [])

    return ((name, config["buildPlans"][name].get("family", name)), styles, nerdfont)


def store_fonts(dest: Path, source: Path):
    dest.mkdir(parents=True, exist_ok=True)
    for font in filter(lambda f: f.is_file(), source.glob("*.ttf")):
        shutil.move(str(source / font), dest)
    print(f"Fonts installed to {dest}", file=sys.stderr)

    subprocess.run(["fc-cache", "--force"]).check_returncode()
    print("Fonts re-cached", file=sys.stderr)


if __name__ == "__main__":
    config_dir = Path(xdg_config_home) / "iosevka"
    cache_dir = Path(xdg_cache_home)
    install_dir = cache_dir / "iosevka"
    font_dir = Path(xdg_data_home) / "fonts"

    install_iosevka(install_dir)
    print(f"Loading font configurations in {config_dir}", file=sys.stderr)
    for conf in filter(
        lambda p: p.suffix in {".ini", ".toml"},
        Path(config_dir).glob("*"),
    ):
        print(f"Found {conf.stem}", file=sys.stderr)

        if conf.suffix == ".ini":
            plan, styles, nerdfont_opts = parse_config_ini(conf)
            family = generate_font_plan(install_dir, plan, styles)
        else:
            (plan, family), styles, nerdfont_opts = parse_config_toml(conf)
            shutil.copy(conf, install_dir / "private-build-plans.toml")

        generate_font(install_dir, plan)
        gen_dir = install_dir / "dist" / plan / "TTF"

        if nerdfont_opts is not None:
            mono = any(filter(lambda o: o in styles["common"], ("sp-term", "sp-fixed")))
            nerdfont_patch(
                gen_dir,
                cache_dir / "nerdfont",
                family,
                options=nerdfont_opts,
                mono=mono,
            )

        store_fonts(font_dir, gen_dir)
