#!/usr/bin/env python3
# summary: Read public status for this account's lock screen.
"""Usage: starchaser lock status [--help]

Returns battery, network connectivity (and whether it is a cable), notification count and the next alarm time.
Notification text and alarm labels are never included.
"""
import json
import os
import subprocess
import sys
from pathlib import Path


def output(args):
    try:
        result = subprocess.run(args, capture_output=True, text=True, timeout=3)
        return result.stdout.strip() if result.returncode == 0 else ''
    except (OSError, subprocess.SubprocessError):
        return ''


def status(power=Path('/sys/class/power_supply')):
    battery = None
    charging = False
    for item in sorted(power.glob('*')):
        try:
            if (item / 'type').read_text().strip() != 'Battery':
                continue
            if (item / 'scope').exists() and (item / 'scope').read_text().strip() == 'Device':
                continue
            if (item / 'present').exists() and (item / 'present').read_text().strip() == '0':
                continue
            battery = max(0, min(100, int((item / 'capacity').read_text())))
            charging = (item / 'status').read_text().strip() == 'Charging'
            break
        except (OSError, ValueError):
            continue
    state = output(['nmcli', '-t', '-f', 'STATE', 'general'])
    connected = state in ('connected', 'connected (local only)', 'connected (site only)')
    # a cable and no Wi-Fi: the lock screen shows an Ethernet mark, not a Wi-Fi one (Fable pre-final P3)
    kinds = [line.split(':') for line in output(['nmcli', '-t', '-f', 'TYPE,STATE', 'device']).splitlines()]
    up = {kind for kind, *rest in kinds if rest and rest[0].startswith('connected')}
    wired = connected and 'ethernet' in up and 'wifi' not in up
    raw = output(['qs', '-p', str(Path.home() / '.config/quickshell/cockpit'), 'ipc', 'call', 'cockpit', 'lockStatus'])
    try:
        data = json.loads(raw)
    except ValueError:
        data = {}
    count = data.get('count', 0) if isinstance(data, dict) else 0
    alarm = data.get('alarm', 0) if isinstance(data, dict) else 0
    return dict(battery=battery, charging=charging, connected=connected, wired=wired,
                count=count if type(count) is int and count >= 0 else 0,
                alarm=alarm if type(alarm) in (int, float) and alarm > 0 else 0)


if __name__ == '__main__':
    if sys.argv[1:] in (['--help'], ['-h']):
        print(__doc__)
    elif sys.argv[1:]:
        print(__doc__, file=sys.stderr)
        sys.exit(2)
    else:
        os.environ['LC_ALL'] = 'C.UTF-8'
        print(json.dumps(status()))
