#!/usr/bin/python3
"""Report a fixed set of live-session checks to the optional virtual test port."""
from pathlib import Path
import json
import os
import shutil
import subprocess
import sys
import time


def report_progress(port):
    """Send only fixed-schema backend telemetry from this explicitly qualified test VM."""
    sys.path.insert(0, '/usr/local/lib/newworld-installer')
    from progress import Journal, STAGES
    import math

    journal = Journal()
    until = time.monotonic() + 6 * 3600
    with port.open('wb', buffering=0) as out:
        while time.monotonic() < until:
            for event in journal.read():
                stage = event.get('stage')
                status = event.get('status')
                ts = event.get('time')
                if stage not in STAGES or status not in ('running', 'success', 'error'):
                    continue
                if not isinstance(ts, (int, float)) or not math.isfinite(ts):
                    continue
                sample = {'stage': stage, 'status': status, 'time': ts}
                fraction = event.get('fraction')
                if isinstance(fraction, (int, float)) and math.isfinite(fraction) and 0 <= fraction <= 1:
                    sample['fraction'] = fraction
                out.write((json.dumps({'install_event': sample}) + '\n').encode('ascii'))
                if status in ('success', 'error'):
                    return
            time.sleep(1)


def main():
    port = Path('/dev/virtio-ports/org.compactdesktop.qualification')
    if not port.exists():
        return
    model = Path('/sys/class/dmi/id/product_name')
    if not model.exists() or model.read_text().strip() != 'Compact Desktop ISO Qualification':
        return

    def succeeds(args):
        try:
            return subprocess.run(args, capture_output=True, timeout=5).returncode == 0
        except (OSError, subprocess.TimeoutExpired):
            return False

    shell_ready = False
    for _ in range(90):
        if succeeds(['busctl', '--user', 'status', 'org.kde.plasmashell']):
            shell_ready = True
            break
        time.sleep(2)
    locales = {line.replace('-', '').casefold() for line in
               subprocess.check_output(['locale', '-a'], text=True).splitlines()}
    desktop_files = list(Path('/usr/share/applications').glob('*.desktop'))
    def desktop_entry(substring):
        return any(substring in f.read_text(errors='replace') for f in desktop_files)
    result = {
        'probe_version': 1,
        'checks': {
            'uefi': Path('/sys/firmware/efi').exists(),
            'live_medium': Path('/run/live/medium').is_mount(),
            'live_graphical_user': os.getuid() != 0,
            'plasma_session_bus': shell_ready,
            'wayland_session': os.environ.get('XDG_SESSION_TYPE') == 'wayland',
            'calamares_executable': shutil.which('calamares') is not None,
            'calamares_application': desktop_entry('calamares'),
            'hebrew_utf8': 'he_il.utf8' in locales,
            'english_utf8': 'en_us.utf8' in locales,
            'compact_settings_entry': os.access('/usr/bin/compact-settings', os.X_OK)
                and Path('/usr/share/applications/compact-settings.desktop').is_file(),
            'apps_setup_entry': os.access('/usr/local/bin/compact-apps', os.X_OK)
                and Path('/usr/share/applications/compact-apps.desktop').is_file(),
            'agreement_gate': os.access('/usr/local/lib/compact-desktop/consent/session-gate', os.X_OK)
                and Path('/etc/sddm.conf.d/85-compact-agreement.conf').is_file(),
        },
    }
    live = 'boot=live' in Path('/proc/cmdline').read_text().split()
    result['session_kind'] = 'live' if live else 'installed'
    result['session_locale'] = {
        key: os.environ.get(key) for key in ('LANG', 'LANGUAGE', 'LC_MESSAGES')
    }
    result['session_locale']['boot_locale'] = next(
        (word for word in Path('/proc/cmdline').read_text().split() if word.startswith('locales=')), None)

    try:
        sys.path.insert(0, '/usr/lib/compact-settings')
        from catalog import CATEGORIES, command_for, installed_modules
        modules = installed_modules(shutil.which('kcmshell6'))
        routes = [(category.key, action) for category in CATEGORIES for action in category.actions]
        result['settings'] = {
            'categories': [category.key for category in CATEGORIES],
            'total_actions': len(routes),
            'unavailable': [f'{key}/{action.en}' for key, action in routes
                            if not command_for(action, modules, 'en')],
        }
    except (ImportError, OSError, ValueError) as error:
        result['settings_error'] = type(error).__name__
    if not live:
        sys.path.insert(0, '/usr/local/lib/compact-desktop/consent')
        from agreement_model import has_agreed
        source = subprocess.run(['findmnt', '-n', '-o', 'SOURCE,FSTYPE', '/'],
                                capture_output=True, text=True, timeout=15)
        result['installed'] = {
            'root_device': source.stdout.strip(),
            'live_media_present': Path('/run/live/medium').is_mount(),
            'account_consent': has_agreed(),
            'release_kernel': os.uname().release,
            'binder_module': succeeds(['/usr/sbin/modinfo', 'binder_linux'])
                or Path('/dev/binderfs').exists()
                or Path('/sys/module/binder_linux').exists(),
        }
    payload = (json.dumps(result) + '\n').encode('ascii')
    # The host can receive results. The software never reads commands from the port.
    for _ in range(30):
        try:
            with port.open('wb', buffering=0) as channel:
                channel.write(payload)
            if live and 'newworld.autoinstall=1' in Path('/proc/cmdline').read_text().split():
                try:
                    report_progress(port)
                except (ImportError, OSError):
                    pass
            return
        except (FileNotFoundError, PermissionError):
            time.sleep(1)


if __name__ == '__main__':
    main()
