#!/usr/bin/env python3
# summary: Read or change date, language, and regional preferences.
"""Date & language preferences.
Usage: starchaser region get | set KEY VALUE | refresh-zone
KEY: timezone, automaticZone (on/off), clock24 (on/off), firstDay (sunday/monday/saturday),
     language, formats (an installed locale), units (imperial/metric).
Language and formats apply to new apps after signing in again.
Automatic time zone uses ipapi.co's internet-address lookup only after opt-in.
"""
import fcntl
import json
import os
import re
import subprocess
import sys
import urllib.request
from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

CONFIG = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config')
DEFAULTS = dict(automaticZone=False, clock24=False, firstDay='sunday', language='en_US.UTF-8', formats='en_US.UTF-8', units='imperial')


def command(*args):
    p = subprocess.run(args, capture_output=True, text=True, timeout=30)
    if p.returncode:
        raise RuntimeError("The change couldn't be applied. Try again or check your account permissions.")
    return p.stdout.strip()


def read():
    try:
        value = json.loads((CONFIG / 'starchaser/region.json').read_text())
        return dict(DEFAULTS, **value) if isinstance(value, dict) else dict(DEFAULTS)
    except (OSError, ValueError):
        return dict(DEFAULTS)


def atomic(path, text):
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_name('.' + path.name + '.' + str(os.getpid()))
    try:
        with temp.open('w') as out:
            out.write(text); out.flush(); os.fsync(out.fileno())
        temp.replace(path)
    finally:
        temp.unlink(missing_ok=True)


def locales():
    return sorted(set(command('locale', '-a').splitlines()) | {'en_US.UTF-8'})


def languages():
    # Offer supported languages even before locale-gen has prepared them.
    try:
        available = {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:
        available = set()
    return sorted(available | set(locales()))


def valid_zone(zone):
    if not isinstance(zone, str) or not re.fullmatch(r'[A-Za-z0-9_+/-]{1,100}', zone):
        raise ValueError('Choose a time zone from the list.')
    try:
        ZoneInfo(zone)
    except (ZoneInfoNotFoundError, ValueError):
        raise ValueError('Choose a time zone from the list.') from None
    return zone


def detect_zone():
    # API: https://ipapi.co/api/#specific-location-field-1. No location lookup while the switch is off.
    request = urllib.request.Request('https://ipapi.co/timezone/', headers={'User-Agent':'Starchaser/1.0'})
    with urllib.request.urlopen(request, timeout=10) as response:
        return valid_zone(response.read(256).decode().strip())


def refresh_zone():
    # The timer is harmless when disabled. Hold the same lock as edits so an old lookup cannot override a newer manual choice.
    with settings_lock():
        if read()['automaticZone']:
            command('timedatectl', 'set-timezone', detect_zone())


def settings_lock():
    import contextlib
    @contextlib.contextmanager
    def locked():
        (CONFIG / 'starchaser').mkdir(parents=True, exist_ok=True)
        with (CONFIG / 'starchaser/.region.lock').open('a') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            yield
    return locked()


def set_value(key, value):
    with settings_lock():
        data = read()
        if key in ('clock24', 'automaticZone'):
            if value not in ('on','off'): raise ValueError('Choose on or off.')
            val = value == 'on'
            if key == 'automaticZone' and val:
                command('timedatectl', 'set-timezone', detect_zone())
        elif key == 'timezone':
            val = valid_zone(value)
            old = command('timedatectl', 'show', '--property=Timezone', '--value')
            command('timedatectl', 'set-timezone', val)
            data['automaticZone'] = False
            data['recentZones'] = list(dict.fromkeys([z for z in [val, old] + data.get('recentZones', []) if z]))[:5]
        elif key in ('language','formats'):
            if not re.fullmatch(r'[a-zA-Z0-9_.@-]+', value) or value not in (languages() if key == 'language' else locales()):
                raise ValueError('Choose an installed language or format from the list.')
            if key == 'language':
                command('pkexec', '/usr/local/lib/starchaser/starchaser-admin', 'language', value)
            val = value
            if key == 'formats':
                data['units'] = 'imperial' if re.search(r'_US(?:\.|$)', value) else 'metric'
        elif key in ('firstDay', 'units'):
            if value not in ({'firstDay':('sunday','monday','saturday'), 'units':('imperial','metric')}[key]):
                raise ValueError('Choose a value from the list.')
            val = value
        else:
            raise ValueError('Unknown date or language setting.')
        data[key] = val
        if key == 'clock24':
            command(str(Path(__file__).resolve().with_name('starchaser-theme')), 'cockpit', 'clock24', value)
        if key in ('language','formats','units'):
            # LC_MEASUREMENT is independent of date/number formats. C.UTF-8 supplies metric
            # measurements even when US formats are selected, without another generated locale.
            variables = {'LANG':data['language'], 'LC_TIME':data['formats'], 'LC_NUMERIC':data['formats'],
                         'LC_MONETARY':data['formats'], 'LC_MEASUREMENT':'en_US.UTF-8' if data['units']=='imperial' else 'C.UTF-8'}
            atomic(CONFIG / 'environment.d/30-starchaser-region.conf', ''.join(f'{k}={v}\n' for k,v in variables.items()))
        atomic(CONFIG / 'starchaser/region.json', json.dumps(data, indent=2)+'\n')


def zone_times(zones, clock24=False, now=None):
    from datetime import datetime, timezone
    from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
    now = now or datetime.now(timezone.utc)
    result = {}
    for zone in zones:
        try:
            local = now.astimezone(ZoneInfo(zone))
            result[zone] = local.strftime('%H:%M' if clock24 else '%I:%M %p').lstrip('0') if not clock24 else local.strftime('%H:%M')
        except (ZoneInfoNotFoundError, ValueError):
            continue
    return result


def zone_names(zones, now=None):
    from datetime import datetime, timezone
    now = now or datetime.now(timezone.utc)
    names = {
        'GMT': 'Greenwich Mean Time', 'UTC': 'Coordinated Universal Time',
        'CET': 'Central European Time', 'CEST': 'Central European Summer Time',
        'EET': 'Eastern European Time', 'EEST': 'Eastern European Summer Time',
        'WET': 'Western European Time', 'WEST': 'Western European Summer Time',
        'BST': 'British Summer Time', 'JST': 'Japan Time', 'KST': 'Korea Time',
        'HKT': 'Hong Kong Time', 'SGT': 'Singapore Time', 'MSK': 'Moscow Time',
        'AEST': 'Australian Eastern Time', 'AEDT': 'Australian Eastern Daylight Time',
        'ACST': 'Australian Central Time', 'ACDT': 'Australian Central Daylight Time',
        'AWST': 'Australian Western Time', 'NZST': 'New Zealand Time',
        'NZDT': 'New Zealand Daylight Time', 'SAST': 'South Africa Time',
        'EAT': 'East Africa Time', 'WAT': 'West Africa Time', 'CAT': 'Central Africa Time',
        'EST': 'Eastern Time', 'EDT': 'Eastern Time', 'MST': 'Mountain Time', 'MDT': 'Mountain Time',
        'PST': 'Pacific Time', 'PDT': 'Pacific Time', 'HST': 'Hawaii Time',
        'AKST': 'Alaska Time', 'AKDT': 'Alaska Time', 'AST': 'Atlantic Time', 'ADT': 'Atlantic Time',
    }
    result = {}
    for zone in zones:
        local = now.astimezone(ZoneInfo(zone))
        abbr = local.tzname()
        name = names.get(abbr)
        if abbr == 'IST':
            name = 'Ireland Time' if zone in ('Europe/Dublin', 'Eire') else 'Israel Time' if zone in ('Asia/Jerusalem', 'Asia/Tel_Aviv', 'Israel') else 'India Time'
        elif abbr == 'PST' and zone == 'Asia/Manila':
            name = 'Philippine Time'
        elif abbr in ('CST', 'CDT'):
            name = 'China Time' if zone.startswith('Asia/') or zone in ('PRC', 'ROC') else 'Cuba Time' if zone in ('America/Havana', 'Cuba') else 'Central Time'
        if not name:
            minutes = int(local.utcoffset().total_seconds() / 60)
            name = f'UTC{"+" if minutes >= 0 else "-"}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}'
        result[zone] = name
    return result


def picker_zones():
    """Search real zones, excluding tzdata's obsolete compatibility links."""
    from zoneinfo import TZPATH, available_timezones
    available = available_timezones()
    for base in TZPATH:
        try:
            lines = (Path(base) / 'tzdata.zi').read_text().splitlines()
        except OSError:
            continue
        zones = {line.split()[1] for line in lines if line.startswith(('Z ', 'Zone '))}
        if zones:
            return sorted(zones & available)
    # zone.tab is distributed with older versions of tzdata, too.
    for base in TZPATH:
        try:
            lines = (Path(base) / 'zone.tab').read_text().splitlines()
        except OSError:
            continue
        return sorted(({line.split()[2] for line in lines if line and not line.startswith('#')} | {'Etc/UTC'}) & available)
    return sorted(available)


def main(args):
    if args in (['-h'], ['--help']): print(__doc__); return
    if args == ['get']:
        from zoneinfo import available_timezones
        data = read()
        data.update(timezone=command('timedatectl','show','--property=Timezone','--value'),
                    locales=locales(), languages=languages(), zones=sorted(available_timezones()), searchZones=picker_zones())
        # The existing clock's setting wins if changed through its right-click menu.
        try: data['clock24'] = json.loads((CONFIG/'starchaser/cockpit.json').read_text()).get('clock24',data['clock24'])
        except (OSError, ValueError): pass
        data['zoneTimes'] = zone_times(data['zones'], data['clock24'])
        data['zoneNames'] = zone_names(data['zones'])
        print(json.dumps(data))
    elif args == ['zone-times']:
        from zoneinfo import available_timezones
        zones = sorted(available_timezones())
        data = read()
        try: data['clock24'] = json.loads((CONFIG/'starchaser/cockpit.json').read_text()).get('clock24', data['clock24'])
        except (OSError, ValueError): pass
        print(json.dumps(dict(times=zone_times(zones, data['clock24']), names=zone_names(zones))))
    elif len(args)==3 and args[0]=='set': set_value(args[1],args[2])
    elif args == ['refresh-zone']: refresh_zone()
    else: raise ValueError('Use get, set KEY VALUE, or refresh-zone.')


if __name__ == '__main__':
    try: main(sys.argv[1:])
    except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
        print(str(error), file=sys.stderr); sys.exit(1)
