#!/usr/bin/env python3
# summary: Choose built-in graphics on a hybrid laptop for the next restart.
"""usage: starchaser graphics status | set on|off | device

Use the built-in graphics for the desktop and ordinary apps on a hybrid laptop.
Restart to apply. Explicit NVIDIA apps can still use NVIDIA; this does not disable its driver.
Display ports wired only to NVIDIA may be unavailable while this is on.
"""
import json
import os
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_device_io import read_json, update_json

# built-in screens: laptops' eDP, older laptops' LVDS, some 2-in-1s' DSI
INTERNAL = ('eDP', 'LVDS', 'DSI')
CONFIG = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'starchaser/graphics.json'


def read(path):
    try:
        return path.read_text().strip()
    except OSError:
        return ''


def hybrid_card(base=Path('/sys')):
    # Like Omarchy's omarchy-hw-hybrid-gpu (MIT), inspect cached sysfs IDs, which do not wake a sleeping GPU.
    laptop = read(base / 'class/dmi/id/chassis_type') in ('8', '9', '10', '14', '31', '32') or any(
        read(p / 'type') == 'Battery' for p in (base / 'class/power_supply').glob('*'))
    cards = [(p, read(p / 'device/vendor')) for p in (base / 'class/drm').glob('card*') if re.fullmatch(r'card\d+', p.name)]
    if not laptop or not any(v == '0x10de' for _, v in cards):
        return ''
    # Require an internal panel wired to this card, avoiding a desktop GPU or a mux in dedicated-only mode.
    for p, vendor in sorted(cards):
        if vendor in ('0x8086', '0x1002') and any(read(c / 'status') == 'connected' for kind in INTERNAL for c in p.glob(f'{p.name}-{kind}-*')):
            return '/dev/dri/' + p.name
    return ''


def main(args):
    if args in (['--help'], ['-h']):
        print(__doc__); return 0
    if args not in (['status'], ['device'], ['set', 'on'], ['set', 'off']):
        print(__doc__, file=sys.stderr); return 2
    try:
        card = hybrid_card()
        if args[0] == 'set':
            if not card:
                raise ValueError('No supported hybrid laptop graphics found.')
            update_json(CONFIG, lambda data: data.update(builtin=args[1] == 'on'))
        saved = read_json(CONFIG)
        desired = isinstance(saved, dict) and saved.get('builtin') is True
        current = os.environ.get('STARCHASER_BUILTIN_GRAPHICS') == '1'
        if args == ['device']:
            if card and desired:
                print(card)
            return 0
        print(json.dumps({'ok': True, 'available': bool(card), 'builtin': desired, 'current': current,
                          'restartRequired': desired != current,
                          'message': 'Restart to apply. Apps explicitly started with NVIDIA still use it. Screen connectors wired only to NVIDIA may be unavailable.'}))
        return 0
    except (OSError, ValueError) as error:
        print(json.dumps({'ok': False, 'errors': str(error)})); return 1


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