#!/usr/bin/env bash
# xcode-touch installer — เปิด mouse capture + scroll สำหรับ xcode TUI บน Termux
# Usage: curl -fsSL https://xcode-cli.vercel.app/mobile/touch/install.sh | bash
set -euo pipefail

RELOAD=1
if [ "${1:-}" = "--no-reload" ]; then RELOAD=0; fi

CONFIG_ROOT="${XDG_CONFIG_HOME:-$HOME/.config}"

apply_with_node() {
  node - "$CONFIG_ROOT" <<'NODE'
const fs = require("fs");
const path = require("path");
const root = process.argv[2];
const stamp = String(Date.now()) + process.hrtime.bigint().toString();

function load(p) {
  try {
    const data = JSON.parse(fs.readFileSync(p, "utf8"));
    return data && typeof data === "object" && !Array.isArray(data) ? data : {};
  } catch {
    return {};
  }
}

function save(p, data) {
  fs.mkdirSync(path.dirname(p), { recursive: true });
  if (fs.existsSync(p)) fs.copyFileSync(p, `${p}.bak.${stamp}`);
  fs.writeFileSync(p, JSON.stringify(data, null, 2) + "\n", "utf8");
}

for (const app of ["xcode", "opencode"]) {
  const p = path.join(root, app, "tui.json");
  const conf = load(p);
  if (!conf.$schema) conf.$schema = "https://opencode.ai/tui.json";
  conf.mouse = true;
  conf.scroll_speed = 5;
  conf.scroll_acceleration = { enabled: true };
  save(p, conf);
}

const cliPath = path.join(root, "xcode", "cli.json");
const cli = load(cliPath);
if (!cli.$schema) cli.$schema = "https://opencode.ai/v2/cli.json";
cli.mouse = true;
const scroll = cli.scroll && typeof cli.scroll === "object" && !Array.isArray(cli.scroll) ? cli.scroll : {};
scroll.speed = 5;
scroll.acceleration = true;
cli.scroll = scroll;
save(cliPath, cli);

console.log("ติดตั้ง config แล้ว:");
console.log(`  ${root}/xcode/tui.json`);
console.log(`  ${root}/xcode/cli.json`);
console.log(`  ${root}/opencode/tui.json`);
NODE
}

apply_with_python() {
  local pybin="$1"
  "$pybin" - "$CONFIG_ROOT" <<'PY'
import json, os, shutil, sys, time

root = sys.argv[1]
stamp = time.time_ns()

def load(path):
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}

def save(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    if os.path.exists(path):
        shutil.copy2(path, f"{path}.bak.{stamp}")
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
        f.write("\n")

for app in ("xcode", "opencode"):
    path = os.path.join(root, app, "tui.json")
    conf = load(path)
    conf.setdefault("$schema", "https://opencode.ai/tui.json")
    conf["mouse"] = True
    conf["scroll_speed"] = 5
    conf["scroll_acceleration"] = {"enabled": True}
    save(path, conf)

path = os.path.join(root, "xcode", "cli.json")
conf = load(path)
conf.setdefault("$schema", "https://opencode.ai/v2/cli.json")
conf["mouse"] = True
scroll = conf.get("scroll")
if not isinstance(scroll, dict):
    scroll = {}
scroll["speed"] = 5
scroll["acceleration"] = True
conf["scroll"] = scroll
save(path, conf)

print("ติดตั้ง config แล้ว:")
print(f"  {root}/xcode/tui.json")
print(f"  {root}/xcode/cli.json")
print(f"  {root}/opencode/tui.json")
PY
}

if command -v node >/dev/null 2>&1; then
  apply_with_node
elif command -v python3 >/dev/null 2>&1; then
  apply_with_python python3
elif command -v python >/dev/null 2>&1; then
  apply_with_python python
else
  if command -v pkg >/dev/null 2>&1; then
    echo "[*] กำลังติดตั้ง python เพื่อ merge config..."
    pkg install -y python
    apply_with_python python
  else
    echo "ต้องมี node หรือ python ก่อน" >&2
    exit 1
  fi
fi

if [ "$RELOAD" = 1 ] && command -v xcode >/dev/null 2>&1; then
  xcode reload >/dev/null 2>&1 || true
  echo "สั่ง xcode reload แล้ว"
fi

echo
echo "ถ้า TUI ยังไม่ตอบสนอง: พิมพ์ /exit แล้วเปิดใหม่ด้วย  xcode -c"
echo "วิธีใช้: ลากนิ้วบนเนื้อหาแชท = เลื่อน, แตะ = คลิก"
