#!/usr/bin/env python3
"""Apply Studio's dock and wallpaper in one isolated bot display's session.
Run inside hermes-display-session, or: hermes-display-env N hermes-display-style.
Live application never restarts the X server, browser, or computer-use driver.
"""
import json
import os
from pathlib import Path
import shutil
import subprocess
import time
from urllib.parse import urlparse, unquote

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
if not os.environ.get('DISPLAY') or not os.environ.get('DBUS_SESSION_BUS_ADDRESS'):
    raise SystemExit('Run inside a bot display environment.')
# Older environment contracts lack XDG paths; Chrome's isolated home identifies them.
state = Path(os.environ['CHROME_CONFIG_HOME']).parent
config = state / 'config'
os.environ.update(XDG_CONFIG_HOME=str(config), XDG_CACHE_HOME=str(state / 'cache'))

# Preserve the pre-migration configuration once. Subsequent boots leave user changes intact.
marker = config / 'studio-desktop-v1.json'
wallpaper = ROOT / 'assets/graphite-fold.png'
workspace = os.environ.get('HERMES_DISPLAY_WORKSPACE')
if not workspace:
    browser_url = os.environ.get('HERMES_DISPLAY_BROWSER_URL', '')
    envfile = Path.home() / '.config/hermes-studio-app/displays' / (os.environ['DISPLAY'].lstrip(':').split('.')[0] + '.env')
    if not browser_url and envfile.exists():
        for line in envfile.read_text().splitlines():
            if line.startswith('HERMES_DISPLAY_BROWSER_URL='): browser_url = line.split('=', 1)[1].strip('\"\'')
    if browser_url.startswith('file://'): workspace = str(Path(unquote(urlparse(browser_url).path)).parent)
workspace = workspace or str(Path.home())

if not marker.exists():
    backup = state / 'backups' / ('desktop-' + time.strftime('%Y%m%d-%H%M%S'))
    backup.mkdir(parents=True, exist_ok=True)
    for relative in ['xfce4/xfconf/xfce-perchannel-xml', 'xfce4/panel', 'gtk-3.0/gtk.css']:
        source = config / relative
        target = backup / relative
        if source.is_dir(): shutil.copytree(source, target)
        elif source.exists():
            target.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(source, target)

    def prop(channel, name, kind, value):
        cmd = ['xfconf-query', '-c', channel, '-p', name]
        exists = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
        if not exists: cmd += ['--create', '--type', kind]
        subprocess.run(cmd + ['--set', str(value).lower() if isinstance(value, bool) else str(value)], check=True, stdout=subprocess.DEVNULL)

    def array(channel, name, kind, values):
        subprocess.run(['xfconf-query', '-c', channel, '-p', name, '--reset', '--recursive'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        cmd = ['xfconf-query', '-c', channel, '-p', name, '--create', '--force-array']
        for value in values: cmd += ['--type', kind, '--set', str(value)]
        subprocess.run(cmd, check=True)

    for number, app, name, icon in [(11, 'browser', 'Browser', 'google-chrome'), (12, 'files', 'Files', 'system-file-manager'), (13, 'terminal', 'Terminal', 'utilities-terminal')]:
        directory = config / f'xfce4/panel/launcher-{number}'
        directory.mkdir(parents=True, exist_ok=True)
        (directory / f'{app}.desktop').write_text(f'[Desktop Entry]\nType=Application\nName={name}\nComment=Open {name.lower()}\nExec="{HERE / "hermes-display-launch"}" {app} "{workspace}"\nIcon={icon}\nTerminal=false\nStartupNotify=false\n')
        prop('xfce4-panel', f'/plugins/plugin-{number}', 'string', 'launcher')
        array('xfce4-panel', f'/plugins/plugin-{number}/items', 'string', [f'{app}.desktop'])
        prop('xfce4-panel', f'/plugins/plugin-{number}/show-label', 'bool', False)
    prop('xfce4-panel', '/plugins/plugin-14', 'string', 'separator')
    prop('xfce4-panel', '/plugins/plugin-14/style', 'uint', 1)
    prop('xfce4-panel', '/plugins/plugin-14/expand', 'bool', False)
    prop('xfce4-panel', '/plugins/plugin-15', 'string', 'showdesktop')
    for name, kind, value in [
        ('position', 'string', 'p=10;x=0;y=0'), ('position-locked', 'bool', True),
        ('size', 'uint', 56), ('icon-size', 'uint', 40), ('length', 'uint', 1),
        ('length-adjust', 'bool', True), ('autohide-behavior', 'uint', 0),
        ('background-style', 'uint', 0), ('disable-struts', 'bool', False),
    ]: prop('xfce4-panel', f'/panels/panel-1/{name}', kind, value)
    array('xfce4-panel', '/panels/panel-1/plugin-ids', 'int', [11, 12, 13, 14, 15])
    prop('xsettings', '/Net/ThemeName', 'string', 'Greybird-dark')
    prop('xsettings', '/Net/IconThemeName', 'string', 'elementary-xfce-darkest')
    prop('xsettings', '/Gtk/FontName', 'string', 'Sans 10')
    prop('xsettings', '/Gtk/CursorThemeSize', 'int', 24)
    prop('xfwm4', '/general/theme', 'string', 'Greybird-dark')
    prop('xfwm4', '/general/use_compositing', 'bool', True)
    prop('xfwm4', '/general/button_layout', 'string', '|HMC')
    cssfile = config / 'gtk-3.0/gtk.css'
    cssfile.parent.mkdir(parents=True, exist_ok=True)
    css = cssfile.read_text() if cssfile.exists() else ''
    css += '''\n/* Hermes Studio dock v1 */
#XfcePanelWindow { background-color: rgba(28, 30, 32, 0.94); border: 1px solid rgba(255, 255, 255, 0.16); border-radius: 16px; }
#XfcePanelWindow button { border-radius: 11px; margin: 4px 3px; padding: 4px; border: none; background: transparent; box-shadow: none; }
#XfcePanelWindow button:hover { background: rgba(255, 255, 255, 0.09); }
#XfcePanelWindow button:active { background: rgba(255, 255, 255, 0.16); }
'''
    cssfile.write_text(css)
    marker.write_text(json.dumps({'version': 1, 'backup': str(backup), 'wallpaper': str(wallpaper)}, indent=2) + '\n')
    print(f'Studio dock configured; original settings saved in {backup}')

settings = json.loads(marker.read_text())
image = settings.get('wallpaper', str(wallpaper))
if shutil.which('feh') and Path(image).is_file():
    subprocess.run(['feh', '--no-fehbg', '--bg-fill', image], check=True)
else:
    print('Wallpaper not applied: install feh and ensure the wallpaper exists.')
