#!/usr/bin/python3
"""Launch the configured kiosk browser on Wayland, or show a non-interactive diagnostic screen."""

import os
from pathlib import Path
import shutil
from urllib.parse import urlparse


APP_OVERRIDE = Path("/srv/kiosk/app/run-application")
DEFAULT_KIOSK = Path("/etc/default/kiosk")
PROFILE_DIR = Path("/srv/kiosk/app/chromium-profile")
DIAGNOSTIC = "/usr/libexec/kiosk-platform/kiosk-diagnostic-screen"
BROWSER_CANDIDATES = ("/usr/bin/ungoogled-chromium", "/usr/bin/chromium")


def read_start_url(path=DEFAULT_KIOSK):
    if not path.is_file():
        return None
    for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, val = line.split("=", 1)
        if key.strip() not in {"HOMEPAGE", "URL", "KIOSK_URL", "START_URL"}:
            continue
        val = val.strip()
        if len(val) >= 2 and val[0] == val[-1] and val[0] in {'"', "'"}:
            val = val[1:-1]
        parsed = urlparse(val)
        if parsed.scheme in {"http", "https"} and parsed.netloc and not any(c.isspace() for c in val):
            return val
    return None


def find_browser():
    for candidate in BROWSER_CANDIDATES:
        if os.access(candidate, os.X_OK):
            return candidate
    for name in ("ungoogled-chromium", "chromium"):
        found = shutil.which(name)
        if found:
            return found
    return None


def main():
    if APP_OVERRIDE.is_file() and os.access(APP_OVERRIDE, os.X_OK):
        os.execv(str(APP_OVERRIDE), [str(APP_OVERRIDE)])

    url = read_start_url()
    browser = find_browser()
    if not url or not browser:
        os.execv(DIAGNOSTIC, [DIAGNOSTIC])

    PROFILE_DIR.mkdir(parents=True, exist_ok=True)
    os.execv(
        browser,
        [
            browser,
            "--ozone-platform=wayland",
            "--kiosk",
            "--no-first-run",
            "--no-default-browser-check",
            f"--user-data-dir={PROFILE_DIR}",
            "--",
            url,
        ],
    )


if __name__ == "__main__":
    main()
