#!/usr/bin/env python3
# summary: Choose the everyday terminal setup for new shells.
"""Choose the everyday terminal setup for new shells.

usage: starchaser shell on|off|status
       starchaser shell smarter on|off|status [--json]
       starchaser shell update-pointer on|off|status [--json]
       starchaser shell icons
The setup adds Ctrl+R history search, z folder jumping, ll, la, .., open, colored
manual pages and a short folder and git prompt. Highlighted identity prompts stay in place.
Smarter ls and cd uses eza and remembered folders. Changes apply to new terminals.
Settings > Terminal > Smarter ls and cd turns both replacements off.
STARCHASER_SHELL=off also disables the setup for a single shell.
"""
import json
import os
import sys
from pathlib import Path


def main(argv):
    if argv in (['--help'], ['-h']):
        print(__doc__)
        return 0
    if argv == ['icons']:
        # Terminals cannot report glyph coverage. Recognize the configured kitty font;
        # unknown terminals stay readable, and people can explicitly choose auto or never.
        icons = os.environ.get('STARCHASER_SHELL_ICONS', '')
        if icons not in ('auto', 'never'):
            font = 'JetBrainsMono Nerd Font'
            config = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'kitty/kitty.conf'
            try:
                for line in config.read_text().splitlines():
                    parts = line.strip().split(None, 1)
                    if len(parts) != 2:
                        continue
                    key, value = parts
                    if key == 'font_family':
                        font = value
                    elif key == 'include' and value in ('theme.conf', '~/.config/kitty/theme.conf'):
                        continue  # Starchaser's generated palette contains colors only.
                    elif key in ('include', 'globinclude', 'envinclude', 'symbol_map'):
                        font = ''  # An unknown personal font configuration: let the person opt in.
            except FileNotFoundError:
                pass
            icons = 'auto' if os.environ.get('TERM') == 'xterm-kitty' and 'nerd' in font.lower() else 'never'
        print(icons)
        return 0
    pointer = bool(argv and argv[0] == 'update-pointer')
    if pointer:
        argv = argv[1:]
    smarter = bool(argv and argv[0] == 'smarter')
    if smarter:
        argv = argv[1:]
    as_json = bool(argv and argv[-1] == '--json')
    if as_json:
        argv = argv[:-1]
    if len(argv) != 1 or argv[0] not in ('on', 'off', 'status'):
        print(__doc__, file=sys.stderr)
        return 2
    file = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / ('starchaser/update-pointer-disabled' if pointer else 'starchaser/smarter-shell-disabled' if smarter else 'starchaser/shell-disabled')
    try:
        if argv[0] == 'off':
            file.parent.mkdir(parents=True, exist_ok=True)
            file.touch()
        elif argv[0] == 'on':
            file.unlink(missing_ok=True)
        enabled = not file.exists()
        print(json.dumps({'enabled': enabled, 'setupEnabled': not file.with_name('shell-disabled').exists()}) if as_json else
              ('Terminal update pointer is ' if pointer else 'Smarter ls and cd is ' if smarter else 'Terminal setup is ') + ('on' if enabled else 'off') + '. Changes apply to new terminals.')
        return 0
    except OSError as error:
        print('Could not save the terminal choice: ' + str(error), file=sys.stderr)
        return 1


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
