#!/usr/bin/env python3

'''
- kvantum:      kvantummanager --set catppuccin-mocha-"$flavor"
                (a kvantum window will pop out if such theme is not installed)

- nwg-look:     edit $HOME/.local/share/nwg-look/gsettings
                nwg-look -a
                nwg-look & manually confirm

- eww:          edit $HOME/.config/eww/eww.scss
                eww reload

- hypr:         edit $HOME/.config/hypr/hyprland/colors.conf
                hyprctl reload

- rofi:         edit $HOME/.config/rofi/config.rasi

- waybar:       edit $HOME/.config/waybar/style.css
                waybar-toggle restart

- oh-my-posh:   edit $HOME/.config/posh_theme.omp.json

- fastfetch:    edit $HOME/.config/fish/post.d/fetch.fish

- mako:         edit $HOME/.config/mako/config
                makoctl reload

- yazi:         cp -f "$path"/../.yazi-themes/catppuccin-mocha-"$flavor".toml ~/.config/yazi/theme.toml

- wlogout:      edit $HOME/.config/wlogout/style.css
                edit $HOME/.config/wlogout/icons/*.svg

- fuzzel:       edit $HOME/.config/fuzzel/fuzzel.ini

- niri:         edit $HOME/.config/niri/config.kdl

- quickshell    qs ipc call colors setPrimary $hex
'''

import os
import sys
from pathlib import Path
import shutil
import argparse
from typing import Callable


FLAVOR_NAME_PLACEHOLDER = "<FLAVOR_NAME>"
FLAVOR_HEX_PLACEHOLDER = "<FLAVOR_HEX>"


PALETTES = {
    "catppuccin-mocha": {
        "rosewater": "f5e0dc",
        "flamingo": "f2cdcd",
        "pink": "f5c2e7",
        "mauve": "cba6f7",
        "red": "f38ba8",
        "maroon": "eba0ac",
        "peach": "fab387",
        "yellow": "f9e2af",
        "green": "a6e3a1",
        "teal": "94e2d5",
        "sky": "89dceb",
        "sapphire": "74c7ec",
        "blue": "89b4fa",
        "lavender": "b4befe",
    },
}

CURRENT_DIR = Path(__file__).resolve().parent.resolve()


def replace_placeholders(file_path: Path, palette: dict[str, str], flavor: str):
    print(f"Applying flavor {flavor} to {file_path}")

    if not file_path.exists():
        print(f"File {file_path} does not exist.")
        raise FileNotFoundError(f"File {file_path} does not exist.")

    with file_path.open('r') as file:
        content = file.read()

    content = content.replace(FLAVOR_NAME_PLACEHOLDER, flavor)
    content = content.replace(FLAVOR_HEX_PLACEHOLDER, palette[flavor])

    with file_path.open('w') as file:
        file.write(content)


def copy_template(src: Path, dist_dir: Path | None) -> Path:
    if dist_dir is None:
        dist_dir = src.parent

    dist = dist_dir / src.name.removesuffix('.template')

    print(f"Copying {src} to {dist}")

    if not dist_dir.exists():
        print(f"Destination directory {dist_dir} does not exist.")
        raise FileNotFoundError(f"Destination directory {dist_dir} does not exist.")
    if not dist_dir.is_dir():
        print(f"Destination {dist_dir} is not a directory.")
        raise NotADirectoryError(f"Destination {dist_dir} is not a directory.")
    if not src.exists():
        print(f"Source file {src} does not exist.")
        raise FileNotFoundError(f"Source file {src} does not exist.")

    shutil.copyfile(src, dist, follow_symlinks=True)
    return dist


def hex2rgb(hex_color: str) -> tuple[int, int, int]:
    return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4))  # type: ignore


def _change_kvantum(_, flavor):
    os.system(f'kvantummanager --set catppuccin-mocha-{flavor}')
    # execute twice to ensure the theme is installed AND applied
    os.system(f'kvantummanager --set catppuccin-mocha-{flavor}')


def _change_nwglook(_, flavor):
    lines: list[str] = []
    with Path.home().joinpath('.local', 'share', 'nwg-look', 'gsettings').open('r') as file:
        content = file.read()
        lines = content.splitlines()
        for i, line in enumerate(lines):
            if line.startswith('gtk-theme'):
                lines[i] = f'gtk-theme=catppuccin-mocha-{flavor}-standard+default'
                break
        else:
            lines.append(f'gtk-theme=catppuccin-mocha-{flavor}-standard+default')

    with Path.home().joinpath('.local', 'share', 'nwg-look', 'gsettings').open('w') as file:
        file.write('\n'.join(lines))

    os.system('nwg-look -a')
    os.system('nwg-look')


def _change_eww(palette: dict[str, str], flavor: str):
    eww_template = Path.home().joinpath('.config', 'eww', 'eww.scss.template')
    eww_dist = copy_template(eww_template, Path.home().joinpath('.config', 'eww'))
    replace_placeholders(eww_dist, palette, flavor)

    os.system('eww reload')


def _change_hypr(palette: dict[str, str], flavor: str):
    hypr_template = Path.home().joinpath('.config', 'hypr', 'hyprland', 'colors.conf.template')
    hypr_dist = copy_template(hypr_template, Path.home().joinpath('.config', 'hypr', 'hyprland'))
    replace_placeholders(hypr_dist, palette, flavor)

    os.system('hyprctl reload')


def _change_rofi(palette: dict[str, str], flavor: str):
    rofi_template = Path.home().joinpath('.config', 'rofi', 'config.rasi.template')
    rofi_dist = copy_template(rofi_template, Path.home().joinpath('.config', 'rofi'))
    replace_placeholders(rofi_dist, palette, flavor)


def _change_waybar(palette: dict[str, str], flavor: str):
    waybar_template = Path.home().joinpath('.config', 'waybar', 'style.css.template')
    waybar_dist = copy_template(waybar_template, Path.home().joinpath('.config', 'waybar'))
    replace_placeholders(waybar_dist, palette, flavor)
    os.system('waybar-toggle restart')


def _change_ohmyposh(palette: dict[str, str], flavor: str):
    posh_template = Path.home().joinpath('.config', 'posh_theme.omp.json.template')
    posh_dist = copy_template(posh_template, Path.home().joinpath('.config'))
    replace_placeholders(posh_dist, palette, flavor)


def _change_fastfetch(palette: dict[str, str], flavor: str):
    fetch_template = Path.home().joinpath('.config', 'fish', 'post.d', 'fetch.fish.template')
    fetch_dist = copy_template(fetch_template, Path.home().joinpath('.config', 'fish', 'post.d'))
    replace_placeholders(fetch_dist, palette, flavor)


def _change_mako(palette: dict[str, str], flavor: str):
    mako_template = Path.home().joinpath('.config', 'mako', 'config.template')
    mako_dist = copy_template(mako_template, Path.home().joinpath('.config', 'mako'))
    replace_placeholders(mako_dist, palette, flavor)

    os.system('makoctl reload')


def _change_yazi(_, flavor):
    yazi_template = CURRENT_DIR / '..' / '.yazi-themes' / f'catppuccin-mocha-{flavor}.toml'
    yazi_dist = Path.home().joinpath('.config', 'yazi', 'theme.toml')
    shutil.copyfile(yazi_template, yazi_dist, follow_symlinks=True)
    print(f"Copied {yazi_template} to {yazi_dist}")


def _change_wlogout(palette: dict[str, str], flavor: str):
    wlogout_template = Path.home().joinpath('.config', 'wlogout', 'style.css.template')
    wlogout_dist = copy_template(wlogout_template, Path.home().joinpath('.config', 'wlogout'))
    replace_placeholders(wlogout_dist, palette, flavor)

    for icon_template in Path.home().joinpath('.config', 'wlogout', 'icons').glob('*.svg.template'):
        icon_dist = copy_template(icon_template, Path.home().joinpath('.config', 'wlogout', 'icons'))
        replace_placeholders(icon_dist, palette, flavor)


def _change_fuzzel(palette: dict[str, str], flavor: str):
    fuzzel_template = Path.home().joinpath('.config', 'fuzzel', 'fuzzel.ini.template')
    fuzzel_dist = copy_template(fuzzel_template, Path.home().joinpath('.config', 'fuzzel'))
    replace_placeholders(fuzzel_dist, palette, flavor)


def _change_niri(palette: dict[str, str], flavor: str):
    niri_template = Path.home().joinpath('.config', 'niri', 'config.kdl.template')
    niri_dist = copy_template(niri_template, Path.home().joinpath('.config', 'niri'))
    replace_placeholders(niri_dist, palette, flavor)


def _change_quickshell(palette: dict[str, str], flavor: str):
    hex_color = palette[flavor]
    os.system(f'qs ipc call colors setPrimary {hex_color}')


apply_theme_funcs: dict[str, Callable[[dict[str, str], str], None]] = {
    'kvantum': _change_kvantum,
    'nwg-look': _change_nwglook,
    'eww': _change_eww,
    'hypr': _change_hypr,
    'rofi': _change_rofi,
    'waybar': _change_waybar,
    'oh-my-posh': _change_ohmyposh,
    'fastfetch': _change_fastfetch,
    'mako': _change_mako,
    'yazi': _change_yazi,
    'wlogout': _change_wlogout,
    'fuzzel': _change_fuzzel,
    'niri': _change_niri,
    'quickshell': _change_quickshell,
}


def extract_color(image_path: str) -> str:
    from colorthief import ColorThief
    return "#{:02x}{:02x}{:02x}".format(*ColorThief(image_path).get_color(quality=10))


def match_color(color: str, palette: dict[str, str]) -> str:
    """ Matches a given color (rrggbb hex) to the closest color in the palette."""
    # HUE distance of the given and returned color must no<t exceed this value
    HUE_THRESHOLD = 60.0  # degrees

    color = color.lower().strip().removeprefix('#')

    # weigh by CCIR 601 luminosity
    fr, fg, fb = 0.299 / 255 / 255, 0.587 / 255 / 255, 0.114 / 255 / 255
    lfr, lfg, lfb = 0.299 / 255, 0.587 / 255, 0.114 / 255

    def color_distance(c1: str, c2: str) -> float:
        r1, g1, b1 = hex2rgb(c1)
        r2, g2, b2 = hex2rgb(c2)
        diff_l = (lfr * (r1 - r2) + lfg * (g1 - g2) + lfb * (b1 - b2))
        diff_r = fr * (r1 - r2) ** 2
        diff_g = fg * (g1 - g2) ** 2
        diff_b = fb * (b1 - b2) ** 2
        return (diff_r + diff_g + diff_b) * 0.75 + diff_l ** 2

    def color_distance_hue(c1: str, c2: str) -> float:
        def rgb2hue(r, g, b) -> float:
            r, g, b = r / 255.0, g / 255.0, b / 255.0
            mx = max(r, g, b)
            mn = min(r, g, b)
            diff = mx - mn

            if diff == 0:
                return 0.0

            if mx == r:
                hue = (g - b) / diff + (6 if g < b else 0)
            elif mx == g:
                hue = (b - r) / diff + 2
            else:
                hue = (r - g) / diff + 4

            return hue * 60
        r1, g1, b1 = hex2rgb(c1)
        r2, g2, b2 = hex2rgb(c2)
        return abs(rgb2hue(r1, g1, b1) - rgb2hue(r2, g2, b2))

    closest_color = min(palette.keys(), key=lambda k: color_distance(color, palette[k]))
    print(f"Matched color {color} to {closest_color}")

    # if the hue distance is too large, rematch
    if color_distance_hue(color, palette[closest_color]) > HUE_THRESHOLD:
        print(f"Color {color} is too far from {closest_color}, rematching'")
    else:
        return closest_color

    closest_color = min(palette.keys(), key=lambda k: color_distance_hue(color, palette[k]))
    print(f"Rematched color {color} to {closest_color}")

    return closest_color


def pick_flavor(palette: dict[str, str]) -> str:
    def is_interactive() -> bool:
        return sys.stdin.isatty() and sys.stdout.isatty()

    def is_truecolor() -> bool:
        colorterm = os.environ.get('COLORTERM', '')
        term = os.environ.get('TERM', '')

        return (
            'truecolor' in colorterm or
            '24bit' in colorterm or
            term.endswith('-256color')
        )

    if is_interactive():
        isTruecolor = is_truecolor()
        print("Available flavors:")
        for i, flavor in enumerate(palette.keys(), 1):
            r, g, b = hex2rgb(palette[flavor])
            if isTruecolor:
                print(f"\033[38;2;{r};{g};{b}m█ {i}. {flavor}: #{palette[flavor]}\033[0m")
            else:
                print(f"{i}. {flavor}")
        while True:
            choice = input("Pick a flavor by number: ")
            if choice.isdigit() and 1 <= int(choice) <= len(palette):
                return list(palette.keys())[int(choice) - 1]
            print("Invalid choice. Try again.")
    else:
        print("No flavor specified.")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description="Change color theme for various applications.")
    parser.add_argument('-i', '--image', type=str, help="Path to the image")
    parser.add_argument('-f', '--flavor', type=str, help="Flavor to apply")
    parser.add_argument('-c', '--color', type=str, help="Color to match from the palette")
    parser.add_argument('arguments', nargs='*',
                        help="List of applications to change the color theme of, or !app to exclude an application. Available apps: " + ', '.join(apply_theme_funcs.keys()))

    arguments = parser.parse_args()

    # for future use, probably
    def parse_palette_name() -> str:
        return "catppuccin-mocha"

    def parse_flavor(palette: dict[str, str]) -> str:
        if arguments.flavor:
            if arguments.flavor not in palette:
                print(f"Unknown flavor: {arguments.flavor}. Available flavors: {', '.join(palette.keys())}")
                sys.exit(1)
            flavor = arguments.flavor
        elif arguments.color:
            flavor = match_color(arguments.color, palette)
            print(f"Matched color: {flavor}")
        elif arguments.image:
            if not Path(arguments.image).exists():
                print(f"Image file {arguments.image} does not exist.")
                sys.exit(1)
            color = extract_color(arguments.image)
            print(f"Extracted color {color} from image {arguments.image}")
            flavor = match_color(color, palette)
            print(f"Extracted color: {flavor}")
        else:
            flavor = pick_flavor(palette)
        return flavor

    def parse_apps() -> list[str]:
        apps = set()
        if not arguments.arguments:
            apps = set(apply_theme_funcs.keys())
        else:
            allExclude = True
            for arg in arguments.arguments:
                if arg[0] == '!':
                    continue
                allExclude = False
                if arg not in apply_theme_funcs:
                    print(f"Unknown app: {arg}. Available apps: {', '.join(apply_theme_funcs.keys())}")
                    sys.exit(1)
                apps.add(arg)

            # If all arguments are exclusions, start with all apps
            if allExclude:
                apps = set(apply_theme_funcs.keys())

        for arg in arguments.arguments:
            if arg[0] == '!':
                print(f"Excluding app: {arg[1:]}")
                app = arg[1:]
                if app not in apply_theme_funcs:
                    print(f"Unknown app to exclude: {app}. Available apps: {', '.join(apply_theme_funcs.keys())}")
                    sys.exit(1)
                apps.discard(app)

        return list(apps)

    palette_name = parse_palette_name()
    palette = PALETTES[palette_name]
    flavor = parse_flavor(palette)
    apps = parse_apps()

    for app in apps:
        func = apply_theme_funcs[app]
        try:
            print(f"Changing color theme of {app} to flavor {flavor}...")
            func(palette, flavor)
            print("Success!\n")
        except Exception as e:
            print(f"Error while tweaking {app}: {e}")

    os.system(f'notify-send -a "change-colortheme" "Color theme changed" "Palette: {palette_name}\nFlavor: {flavor}"')


if __name__ == "__main__":
    main()
