#!/usr/bin/env python3
# summary: Open a website as an app window.
"""starchaser webapp: open a website as an app window (no tabs, no address bar), for your saved websites, the music app, and the AI slots.

    starchaser webapp show                         add a website with a small form
    starchaser webapp add NAME URL [ICON]          add a website to Apps
    starchaser webapp remove ID | list             remove or list your website apps
    starchaser webapp launch ID                    open a saved website app
    starchaser webapp <url> [--name NAME] [--private]   open it
    starchaser webapp browser               JSON: the browser app windows would use ({"id", "app": bool})
    starchaser webapp require-browser       offer a browser if none is installed; exit 0 when one is available
    starchaser webapp has-browser           check for a browser without offering to install one

How: a site already installed as an app from the browser (a .desktop entry whose name is NAME and that starts the
browser with --app-id) is started as itself, so it keeps its own icon and window. Otherwise a Chromium-family browser
opens the address in its app mode (--app=URL): the default browser when it is one, else the first one installed
(Starchaser's own browser first). With none, the address opens in the default browser like any link.
With --private, installed site apps are skipped. App windows use a separate, saved profile of their own, so they
remember sign-ins without asking to unlock the keyring. The normal browser profile is unchanged.
A new music profile first opens a regular browser window for its one-time setup,
except Chromium, whose empty terms screen is skipped in the music profile.
Your music app opens in its own window when setup finishes, or after ten minutes.
"""
import configparser
import fcntl
import json
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
from urllib.parse import urlsplit

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams, takes_nothing_after

safe_streams()

HOME = Path.home()
# commands of browsers that have an app mode (Chromium family), Starchaser's own first; desktop id -> command
CHROMIUM = [("brave-origin", "brave-origin"), ("brave-browser", "brave"), ("brave", "brave"),
            ("chromium", "chromium"), ("google-chrome", "google-chrome-stable"), ("vivaldi-stable", "vivaldi-stable"),
            ("microsoft-edge", "microsoft-edge-stable"), ("helium", "helium-browser"),
            ("io.github.ungoogled_software.ungoogled_chromium", "flatpak run io.github.ungoogled_software.ungoogled_chromium"),
            ("org.chromium.Chromium", "flatpak run org.chromium.Chromium"),
            ("com.brave.Browser", "flatpak run com.brave.Browser")]
BROWSER_NAMES = {"brave-origin": "Brave", "brave-browser": "Brave", "brave": "Brave",
                 "com.brave.Browser": "Brave", "chromium": "Chromium", "org.chromium.Chromium": "Chromium",
                 "google-chrome": "Google Chrome", "vivaldi-stable": "Vivaldi", "microsoft-edge": "Microsoft Edge",
                 "helium": "Helium", "ungoogled": "Chromium",
                 "io.github.ungoogled_software.ungoogled_chromium": "Chromium"}
SETUP_FD = "STARCHASER_MUSIC_SETUP_FD"
SETUP_WINDOWS = "STARCHASER_MUSIC_SETUP_WINDOWS"


def app_dirs() -> list:
    data = [os.environ.get("XDG_DATA_HOME") or str(HOME / ".local/share")]   # set-but-empty counts as unset
    data += os.environ.get("XDG_DATA_DIRS", "/usr/local/share:/usr/share").split(":")
    data += [str(HOME / ".local/share/flatpak/exports/share"), "/var/lib/flatpak/exports/share"]
    seen, out = set(), []
    for d in data:
        p = Path(d) / "applications"
        if d and p.is_dir() and p not in seen:
            seen.add(p)
            out.append(p)
    return out


def desktop_entry(path: Path) -> dict:
    cp = configparser.ConfigParser(interpolation=None, strict=False)
    try:
        cp.read(path, encoding="utf-8")
        return dict(cp["Desktop Entry"])
    except (configparser.Error, KeyError, OSError, UnicodeDecodeError):
        return {}


def find_app(names: list, exclude_terminal: bool = True) -> Path | None:
    """The first installed, visible .desktop entry whose Name is one of `names` (case ignored)."""
    want = {n.lower() for n in names}
    for d in app_dirs():
        for f in sorted(d.glob("*.desktop")):
            e = desktop_entry(f)
            if not e or e.get("type", "Application") != "Application" or e.get("nodisplay", "").lower() == "true" \
                    or e.get("hidden", "").lower() == "true":
                continue
            if exclude_terminal and e.get("terminal", "").lower() == "true":
                continue
            if e.get("name", "").strip().lower() in want:
                tryexec = e.get("tryexec", "")
                if tryexec and not shutil.which(tryexec):
                    continue
                return f
    return None


def launch_desktop(path: Path) -> bool:
    """Start an app from its .desktop file (gio does the Exec line's field codes properly)."""
    if not shutil.which("gio"):
        return False
    return spawn(["gio", "launch", str(path)])


def spawn(cmd: list, **kwargs) -> bool:
    from starchaser_app_privacy import mediated_command
    try:
        subprocess.Popen(mediated_command(cmd), start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **kwargs)
        return True
    except OSError:
        return False


def default_browser() -> str:
    try:
        r = subprocess.run(["xdg-settings", "get", "default-web-browser"], capture_output=True, text=True, timeout=5)
        return r.stdout.strip().removesuffix(".desktop")
    except (OSError, subprocess.TimeoutExpired):
        return ""


def flatpak_has(app: str) -> bool:
    return any((Path(d) / "app" / app).is_dir() for d in (HOME / ".local/share/flatpak", Path("/var/lib/flatpak")))


def usable(cmd: str) -> bool:
    parts = cmd.split()
    if parts[0] == "flatpak":
        return bool(shutil.which("flatpak")) and flatpak_has(parts[-1])
    return bool(shutil.which(parts[0]))


def browser() -> tuple:
    """(desktop id, command) of the Chromium-family browser to use, or ("", "")."""
    dflt = default_browser()
    for did, cmd in CHROMIUM:
        if did == dflt and usable(cmd):
            return did, cmd
    for did, cmd in CHROMIUM:
        if usable(cmd):
            return did, cmd
    return "", ""


def require_browser(offer=True) -> bool:
    if browser()[1] or default_browser():
        return True
    if offer:
        subprocess.run(["starchaser", "software", "offer", "--remind", "brave-origin",
                        "This step needs a web browser. Install one, then try again."],
                       capture_output=True, check=False)
    return False


def saved_app_id() -> str:
    value = os.environ.get("STARCHASER_WEBAPP_ID", "")
    return value if re.fullmatch(r"webapp-[a-z0-9-]{1,64}", value) else ""


def music_profile() -> Path:
    # the help's separate saved profile: $XDG_DATA_HOME/starchaser/music-browser (or
    # ~/.local/share/starchaser/music-browser), opened with --password-store=basic so it can keep sign-ins
    # without asking to unlock the keyring
    data = Path(os.environ.get("XDG_DATA_HOME") or HOME / ".local/share")
    if saved_app_id():
        return data / "starchaser/webapps" / saved_app_id()
    return data / "starchaser/music-browser"


def profile_ready(profile: Path, browser_id: str = "") -> bool:
    if not (profile / "First Run").is_file():
        return False
    if browser_id != "brave-origin":
        return True
    # Origin writes Chromium's sentinel before its own setup dialog is answered. Only read the
    # acceptance saved by Brave itself; never accept its free tier or purchase on the person's behalf.
    try:
        origin = json.loads((profile / "Local State").read_text())["brave"]["origin"]
        return origin.get("free_tier_accepted") is True or origin.get("purchase_validated") is True
    except (OSError, ValueError, KeyError, TypeError, AttributeError):
        return False


def setup_lock(profile: Path):
    """Keep the setup lock open until the waiter finishes; a busy lock means it already exists."""
    inherited = os.environ.pop(SETUP_FD, "")
    lock = os.fdopen(int(inherited), "a") if inherited else (profile.parent / (profile.name + "-setup.lock")).open("a")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        lock.close()
        return None
    except OSError:
        lock.close()
        raise
    return lock


def request_file(profile: Path) -> Path:
    return profile.parent / (profile.name + "-setup.request")


def window_clients() -> list | None:
    try:
        result = subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True, timeout=5)
        clients = json.loads(result.stdout)
        if result.returncode == 0 and isinstance(clients, list) and all(isinstance(c, dict) for c in clients):
            return clients
    except (OSError, ValueError, subprocess.TimeoutExpired):
        pass
    return None


def uses_profile(client: dict, profile: Path) -> bool:
    try:
        args = Path(f"/proc/{int(client['pid'])}/cmdline").read_bytes().split(b"\0")
        return os.fsencode(f"--user-data-dir={profile}") in args
    except (OSError, KeyError, TypeError, ValueError):
        return False


def blank_title(title: str) -> bool:
    # An empty or generic browser title is not evidence of an untouched blank page.
    return title == "about:blank" or title in {f"about:blank - {name}" for name in BROWSER_NAMES.values()}


class SetupWindow:
    """Own only a new blank window from this launch's dedicated profile; forget it on navigation."""
    def __init__(self, profile: Path, before: list | None):
        self.profile = profile
        self.before = None if before is None else {c.get("address") for c in before}
        self.window = None

    def observe(self, clients: list | None):
        if self.before is None:
            return
        if clients is None:
            self.before = None             # lost visibility: never guess ownership later
            self.window = None
            return
        if self.window:
            if not any(c.get("address") == self.window["address"] and c.get("pid") == self.window["pid"]
                       and blank_title(c.get("title", "")) and uses_profile(c, self.profile) for c in clients):
                self.before = None         # closed, replaced, or navigated: never reclaim it
                self.window = None
            return
        browser_classes = {s.lower() for did, cmd in CHROMIUM for s in (did, cmd.split()[-1])}
        candidates = [c for c in clients if c.get("address") not in self.before
                      and c.get("class", "").lower() in browser_classes and uses_profile(c, self.profile)]
        blank = [c for c in candidates if re.fullmatch(r"0x[0-9a-fA-F]+", c.get("address", ""))
                 and blank_title(c.get("initialTitle", "")) and blank_title(c.get("title", ""))]
        if len(candidates) == len(blank) == 1:
            self.window = blank[0]
        elif candidates:
            self.before = None             # ambiguous or already used: never claim a later user window

    def finish(self, url: str):
        if self.before is None:
            return
        host = urlsplit(url).hostname
        for _ in range(30):
            clients = window_clients()
            self.observe(clients)
            if self.before is None:
                return
            if self.window and any(c.get("address") not in self.before | {self.window["address"]}
                                   and uses_profile(c, self.profile)
                                   and any(c.get(key) == host or (saved_app_id() and c.get(key) == saved_app_id()) or f"-{host}__" in c.get(key, "") or f"-{host}-" in c.get(key, "")
                                           for key in ("class", "initialClass")) for c in clients):
                # Close this address gracefully, without focusing it or ending the browser process.
                try:
                    subprocess.run(["hyprctl", "eval", 'hl.dispatch(hl.dsp.window.close({ window = "address:'
                                    + self.window["address"] + '" }))'], capture_output=True, timeout=5)
                except (OSError, subprocess.TimeoutExpired):
                    pass
                return
            time.sleep(1)


def after_setup(url: str, name: str = "") -> bool:
    profile = music_profile()
    try:
        profile.mkdir(parents=True, exist_ok=True)
        lock = setup_lock(profile)
    except (OSError, ValueError):
        return False
    if lock is None:
        return True
    with lock:
        try:
            before = json.loads(os.environ.pop(SETUP_WINDOWS, "null"))
            if not isinstance(before, list) or not all(isinstance(c, dict) for c in before):
                before = None
        except ValueError:
            before = None
        setup = SetupWindow(profile, before)
        browser_id, _ = browser()
        deadline = time.monotonic() + 600
        while not profile_ready(profile, browser_id) and time.monotonic() < deadline:
            if setup.before is not None:
                setup.observe(window_clients())
            time.sleep(1)
        # A later press during setup (for example another music app) replaces the first request.
        try:
            newer = request_file(profile).read_text().split("\n", 1)
            request_file(profile).unlink(missing_ok=True)
            if newer[0].startswith(("https://", "http://")):
                url, name = newer[0], (newer[1] if len(newer) > 1 else "")
        except OSError:
            pass
        # On timeout, try the app anyway instead of starting another setup cycle.
        opened = open_webapp(url, name, private=True, _setup=False)
        if opened:
            setup.finish(url)
        return opened


def open_webapp(url: str, name: str = "", private: bool = False, _setup: bool = True) -> bool:
    if name and not private:
        f = find_app([name])
        # only an installed site app (the browser's own "install as app"), never some other program that happens to
        # carry the same name: that one is the caller's business (the AI slots look for desktop apps themselves)
        if f and "--app-id=" in desktop_entry(f).get("exec", "") and launch_desktop(f):
            return True
    did, cmd = browser()
    if cmd:
        flags = []
        skip_setup = private and did in ("chromium", "org.chromium.Chromium")
        if private:
            profile = music_profile()
            try:
                profile.mkdir(parents=True, exist_ok=True)
            except OSError:
                return False
            flags = [f"--user-data-dir={profile}", "--password-store=basic"]
            if saved_app_id():
                flags.append("--profile-directory=" + saved_app_id())
            if skip_setup:
                # Chromium's unbranded first run asks to accept an empty document. Skip it only in our
                # music profile; other browsers may have real setup questions or terms to review.
                flags.append("--no-first-run")
        argv = cmd.split()
        if private and argv[:2] == ["flatpak", "run"]:
            argv.insert(2, f"--filesystem={profile}")     # a sandboxed browser can only keep a profile it may write
        if private and _setup and not skip_setup and not profile_ready(profile, did):
            try:
                lock = setup_lock(profile)
            except OSError:
                return False
            if lock is None:
                try:                              # the waiter is running: it opens this newest request instead
                    request_file(profile).write_text(url + "\n" + name)
                except OSError:
                    pass
            else:
                with lock:
                    before = window_clients()
                    if not spawn([*argv, *flags, "--new-window", "about:blank"]):
                        return False
                    try:
                        request_file(profile).unlink(missing_ok=True)
                    except OSError:
                        pass
                    friendly = BROWSER_NAMES.get(did, "your browser")
                    spawn([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", f"Set up {friendly} first",
                           f"{friendly} needs a one-time setup before {name or 'your music app'} can open in its own window. "
                           f"Answer its questions; {name or 'your music app'} opens when you finish."])
                    # Hand the locked descriptor to the detached waiter so even simultaneous opens cannot race.
                    spawn([sys.executable, str(Path(__file__).resolve()), "--after-setup", url, name],
                          pass_fds=(lock.fileno(),), env=dict(os.environ, **{SETUP_FD: str(lock.fileno()),
                                                                          SETUP_WINDOWS: json.dumps(before)}))
            return True
        return spawn([*argv, *flags, f"--app={url}"])
    if not default_browser():
        return False                         # no web browser at all: the caller says so
    return spawn(["xdg-open", url])


if __name__ == "__main__":
    a = sys.argv[1:]
    from starchaser_personal_apps import main as personal_main
    if not any(arg in ("--help", "-h") for arg in a):
        code = personal_main("webapp", a)
        if code is not None:
            sys.exit(code)
    if a[:1] in (["-h"], ["--help"], ["help"]) or any(x in ("-h", "--help") for x in a[1:]):
        print(__doc__.strip())
        sys.exit(0)
    if a[:1] == ["browser"]:
        if len(a) > 1:
            sys.exit(takes_nothing_after("starchaser webapp", "browser", a))
        did, cmd = browser()
        print(json.dumps({"id": did, "app": bool(cmd)}))
        sys.exit(0)
    if a[:1] in (["require-browser"], ["has-browser"]):
        if len(a) > 1:
            sys.exit(takes_nothing_after("starchaser webapp", a[0], a))
        sys.exit(0 if require_browser(offer=a[0] == "require-browser") else 1)
    if a[:1] == ["--after-setup"] and len(a) == 3 and a[1].startswith(("https://", "http://")):
        sys.exit(0 if after_setup(a[1], a[2]) else 1)
    if a and a[0].startswith("-"):
        if a[0] in ("--private", "--name"):
            # documented options in the wrong place: say so, never "unknown"
            print("starchaser webapp: put the web address first: starchaser webapp <url> [--name NAME] [--private]. "
                  "Run 'starchaser webapp --help' for more help.", file=sys.stderr)
        else:
            print(f"starchaser webapp: unknown option '{a[0]}'. Run 'starchaser webapp --help' for more help.", file=sys.stderr)
        sys.exit(2)
    if not a or not a[0].startswith(("https://", "http://")):
        print("starchaser webapp: give a web address (https://…). Run 'starchaser webapp --help' for more help.", file=sys.stderr)
        sys.exit(2)
    # validate every token after the URL; only --private and --name <value> are allowed
    name, private, i = "", False, 1
    while i < len(a):
        if a[i] == "--private":
            private = True
        elif a[i] == "--name" and i + 1 < len(a):
            i += 1
            name = a[i]
        else:
            print(f"starchaser webapp: unknown option '{a[i]}'. Run 'starchaser webapp --help' for more help.", file=sys.stderr)
            sys.exit(2)
        i += 1
    if open_webapp(a[0], name, private=private):
        sys.exit(0)
    if not browser()[1] and not default_browser():
        print("starchaser webapp: no web browser is installed. Get one in Settings > Software.", file=sys.stderr)
    sys.exit(1)
