#!/usr/bin/env python3
"""Dock actions stay on this display; activate an existing app before launching."""
import os
from pathlib import Path
import subprocess
import sys
import sqlite3
import re
HERE = Path(__file__).resolve().parent
kind = sys.argv[1] if len(sys.argv) > 1 else ''
workspace = sys.argv[2] if len(sys.argv) > 2 else os.environ.get('HERMES_DISPLAY_WORKSPACE', str(Path.home()))
classes = {'browser': 'google-chrome', 'files': 'thunar', 'terminal': 'xfce4-terminal'}
if kind not in classes or not os.environ.get('DISPLAY'):
    raise SystemExit('usage: hermes-display-launch browser|files|terminal (inside a bot display)')
# Newly provisioned bots may have no browser autostart URL. Resolve their
# assigned workspace from the app's roster instead of opening the user's home.
if workspace == str(Path.home()):
    database = Path.home() / '.local/share/hermes-studio-app/studio.db'
    if database.exists():
        try:
            with sqlite3.connect(f'file:{database}?mode=ro', uri=True) as db:
                row = db.execute('SELECT id FROM bots WHERE display=?', (int(os.environ['DISPLAY'].lstrip(':').split('.')[0]),)).fetchone()
            if row and re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,63}', row[0]):
                home = Path.home() / '.local/share/hermes-studio-app/hermes'
                workspace = str((home if row[0] == 'default' else home / 'profiles' / row[0]) / 'workspace')
                Path(workspace).mkdir(parents=True, exist_ok=True)
        except (sqlite3.Error, ValueError): pass
windows = subprocess.check_output(['wmctrl', '-lx'], text=True)
for line in windows.splitlines():
    parts = line.split(None, 4)
    if len(parts) >= 4 and classes[kind] in parts[2].lower():
        subprocess.run(['wmctrl', '-ia', parts[0]], check=True)
        raise SystemExit(0)
if kind == 'browser': command = [str(HERE / 'hermes-display-chrome')]
elif kind == 'files': command = ['thunar', workspace]
else: command = ['xfce4-terminal', '--disable-server', '--working-directory', workspace]
os.execvp(command[0], command)
