#!/bin/bash
# anolis:summary=Register the Anolis skill and pin CLI auto-update settings
# anolis:args=[--bindings]
set -euo pipefail
source /usr/libexec/anolis-agent/env
if [[ $# -gt 1 || ( $# == 1 && $1 != --bindings ) ]]; then
  echo 'Usage: anolis agent setup [--bindings]' >&2
  exit 1
fi
mkdir -p "$HOME/Work" "$HOME/.config/anolis/defaults"
for directory in "$HOME/.qwen/skills" "$HOME/.qoder/skills"; do
  mkdir -p "$directory"
  target="$directory/anolis-desktop"
  if [[ -e $target || -L $target ]]; then
    printf 'Keeping existing skill: %s\n' "$target"
  else
    ln -s /usr/share/anolis-agent/skills/anolis-desktop "$target"
    printf 'Registered skill: %s\n' "$target"
  fi
done
python3 - <<'PY'
import datetime,json,os
from pathlib import Path
for name in ('.qwen','.qoder'):
    path=Path.home()/name/'settings.json'
    data=json.loads(path.read_text()) if path.exists() else {}
    if not isinstance(data,dict) or not isinstance(data.get('general',{}),dict):
        raise SystemExit('Unsupported existing settings structure: '+str(path))
    if data.get('general',{}).get('enableAutoUpdate') is False:
        print('Automatic updates already disabled:',path)
        continue
    if path.exists():
        backup=path.with_name('settings.json.before-anolis-'+datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        backup.write_bytes(path.read_bytes())
        backup.chmod(0o600)
    data.setdefault('general',{})['enableAutoUpdate']=False
    temporary=path.with_name('.settings.json.anolis-new')
    temporary.write_text(json.dumps(data,indent=2)+'\n')
    temporary.chmod(0o600)
    os.replace(temporary,path)
    print('Disabled automatic CLI updates for this pinned experiment:',path)
PY
if [[ ${1:-} == --bindings ]]; then
  python3 - <<'PY'
from pathlib import Path
import datetime,shutil
directory=Path.home()/'.config/hypr'
main=directory/'hyprland.lua'
if not main.is_file(): raise SystemExit('Existing hyprland.lua missing; no binding changes made')
line='hl.bind("SUPER + CTRL + SHIFT + A", hl.dsp.exec_cmd("anolis agent"))'
text=main.read_text()
if line not in text:
    shutil.copy2(main,main.with_name('hyprland.lua.before-anolis-agent-'+datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')))
    main.write_text(text.rstrip()+'\n'+line+'\n')
print('Agent binding: Super+Ctrl+Shift+A')
PY
fi
