#!/usr/bin/env python3
"""Manage colors for the AppendHub Desktop Kitty session."""
import re
import sys
from pathlib import Path

CONF_DIR = Path.home() / '.config' / 'brack-terminal'
CONF_FILE = CONF_DIR / 'kitty.conf'
THEMES = {
    'royal': ('#210D34', '#F3E8FF', '#7851A9', '#7851A9'),
    'amethyst': ('#180F25', '#EDE2FF', '#D9A5FF', '#A55CFF'),
    'mint': ('#0D1F1B', '#D9FFF1', '#70E0B3', '#40C99B'),
    'amber': ('#20160B', '#FFF0D4', '#FFC879', '#D99635'),
    'mono': ('#111111', '#EDEDED', '#FFFFFF', '#AAAAAA'),
    'light': ('#F4EFF9', '#2A1737', '#6A0DAD', '#7B2CBF'),
}
HEX = re.compile(r'^#[0-9a-fA-F]{6}$')


def save(bg, fg, cursor, accent):
    CONF_DIR.mkdir(parents=True, exist_ok=True)
    CONF_FILE.write_text(
        '# AppendHub Desktop theme (managed by brack-color)\n'
        f'background {bg}\nforeground {fg}\ncursor {cursor}\n'
        f'selection_background {accent}\nselection_foreground {bg}\n'
        f'color0 {bg}\ncolor7 {fg}\ncolor4 {accent}\ncolor5 {cursor}\n'
        'font_size 13.0\n'
        'confirm_os_window_close 0\n', encoding='utf-8')
    print(f'Colors saved to {CONF_FILE}')
    print('In AppendHub Desktop, press Ctrl+Shift+F5 to reload the theme.')
    print('You can also log out and log back in.')


def main():
    args = sys.argv[1:]
    if not args or args == ['list']:
        print('Themes: ' + ', '.join(THEMES))
        print('Use: brack-color royal')
        print('     brack-color custom #BACKGROUND #TEXT [#CURSOR]')
        print('Then press Ctrl+Shift+F5 in Kitty to apply.')
        return 0
    if len(args) == 1 and args[0] in THEMES:
        save(*THEMES[args[0]])
        return 0
    if args[0] == 'custom' and len(args) in (3, 4) and all(HEX.fullmatch(a) for a in args[1:]):
        bg, fg = args[1:3]
        cursor = args[3] if len(args) == 4 else fg
        save(bg, fg, cursor, cursor)
        return 0
    print('Invalid theme or colors. Type brack-color list for help.', file=sys.stderr)
    return 2


if __name__ == '__main__':
    sys.exit(main())
