#!/usr/bin/env python3
# summary: Read or change the computer's clock and language.
"""Read and change the computer's clock and language through the system services."""
import datetime
import json
import re
import subprocess
import sys
from pathlib import Path


def run(*args):
    result = subprocess.run(args, capture_output=True, text=True, timeout=30, check=False)
    if result.returncode:
        raise ValueError(result.stderr.strip() or "The system service couldn't apply that change.")
    return result.stdout.strip()


def status():
    values = dict(line.split('=', 1) for line in run('timedatectl', 'show', '--property=Timezone', '--property=NTP').splitlines() if '=' in line)
    locale = run('localectl', 'status')
    match = re.search(r'LANG=([^\s]+)', locale)
    return {'timezone': values.get('Timezone', ''), 'automatic': values.get('NTP') == 'yes',
            'language': match[1] if match else 'en_US.UTF-8'}


def available_languages():
    try:
        values = {line.lstrip("# ").split()[0] for line in Path("/etc/locale.gen").read_text().splitlines()
                  if re.fullmatch(r"#?\s*[a-z]{2,3}_[A-Z]{2}\.UTF-8(?:@[A-Za-z0-9_-]+)?\s+UTF-8\s*", line)}
    except OSError:
        values = set()
    return sorted(values or run("localectl", "list-locales").splitlines())


def change(kind, value):
    if kind == 'timezone':
        if value not in run('timedatectl', 'list-timezones').splitlines():
            raise ValueError('Choose a time zone from the list.')
        run('timedatectl', 'set-timezone', value)
    elif kind == 'automatic':
        if value not in ('on', 'off'):
            raise ValueError('Choose on or off.')
        run('timedatectl', 'set-ntp', 'true' if value == 'on' else 'false')
    elif kind == 'date':
        if status()['automatic']:
            raise ValueError('Turn off automatic time before setting the date and time.')
        try:
            date = datetime.datetime.strptime(value, '%m/%d/%Y %I:%M %p')
        except ValueError:
            raise ValueError('Enter a date and time like 11/10/2026 3:30 PM.') from None
        run('timedatectl', 'set-time', date.strftime('%Y-%m-%d %H:%M:%S'))
    elif kind == 'language':
        if value not in available_languages() or not re.fullmatch(r'[A-Za-z0-9_.@-]+', value):
            raise ValueError('Choose an installed language from the list.')
        run('pkexec', '/usr/local/lib/starchaser/starchaser-admin', 'language', value)
    else:
        raise ValueError('Unknown setting.')


def main(args):
    if args in (['--help'], ['-h']):
        print('Usage: starchaser date language get|zones|languages\n       starchaser date language timezone|automatic|date|language VALUE')
        return 0
    if not args or args[0] not in ('get', 'zones', 'languages', 'timezone', 'automatic', 'date', 'language') or len(args) != (1 if args[0] in ('get', 'zones', 'languages') else 2):
        print('Choose get, zones, languages, timezone, automatic, date, or language. See --help.', file=sys.stderr)
        return 2
    try:
        if args[0] == 'get':
            result = status()
        elif args[0] in ('zones', 'languages'):
            result = run('timedatectl', 'list-timezones').splitlines() if args[0] == 'zones' else available_languages()
        else:
            change(*args)
            result = {"ok": True, **status()}
        print(json.dumps(result))
        return 0
    except (OSError, ValueError, subprocess.SubprocessError) as error:
        print(json.dumps({"ok": False, "errors": str(error)}))
        print(str(error), file=sys.stderr)
        return 1


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