#!/usr/bin/env bash
# xcode-mobile one-command installer for Termux on Android (arm64)
# ติดตั้ง xcode + glibc runtime + libsixel + Touch/Scroll fix + Termux extra-keys
# Usage:
#   curl -fsSL https://xcode-cli.vercel.app/mobile/install.sh | bash
set -euo pipefail

BASE_XCODE="${XCODE_UPDATE_URL:-https://xcode-cli.vercel.app}"
BASE_XCODE="${BASE_XCODE%/}"
MOBILE_SITE="${XCODE_MOBILE_URL:-https://xcode-cli.vercel.app/mobile}"
MOBILE_SITE="${MOBILE_SITE%/}"
INSTALL_TOUCH_ONLY=0
SKIP_EXTRA_KEYS=0

for arg in "$@"; do
  case "$arg" in
    --touch-only) INSTALL_TOUCH_ONLY=1 ;;
    --skip-extra-keys) SKIP_EXTRA_KEYS=1 ;;
    -h|--help)
      cat <<'EOF'
xcode-mobile installer for Termux (Android aarch64)

Options:
  --touch-only        Apply touch/scroll config & extra-keys without reinstalling xcode binary
  --skip-extra-keys   Do not overwrite ~/.termux/termux.properties
  -h, --help          Show this help message
EOF
      exit 0
      ;;
  esac
done

if [ -z "${TERMUX_VERSION:-}" ] && [ ! -d /data/data/com.termux ]; then
  echo "x สคริปต์นี้สำหรับ Termux บน Android เท่านั้น" >&2
  exit 1
fi

printf '\n  \033[36m◆ xcode-mobile\033[0m  \033[90mTermux · Sixel · Touch Edition\033[0m\n\n'

# 1. Install base xcode (Termux glibc loader + linux-arm64 binary)
if [ "$INSTALL_TOUCH_ONLY" = 0 ]; then
  echo "  [1/4] ติดตั้ง xcode (Termux linux-arm64 + glibc loader)..."
  curl -fsSL "$BASE_XCODE/install.sh" | bash
else
  echo "  [1/4] ข้ามการติดตั้ง xcode (--touch-only)"
fi

# 2. Install libsixel & useful Termux packages
echo "  [2/4] ตรวจสอบและติดตั้ง libsixel / curl / ca-certificates..."
if command -v pkg >/dev/null 2>&1; then
  pkg install -y curl libsixel ca-certificates >/dev/null 2>&1 || true
fi

# 3. Apply Touch + Scroll config (merge into tui.json & cli.json)
echo "  [3/4] ตั้งค่า Touch & Scroll (mouse: true, scroll speed: 5)..."
CONFIG_ROOT="${XDG_CONFIG_HOME:-$HOME/.config}"

ensure_json_runtime() {
  if command -v node >/dev/null 2>&1 || command -v python3 >/dev/null 2>&1 || command -v python >/dev/null 2>&1; then
    return 0
  fi
  if command -v pkg >/dev/null 2>&1; then
    pkg install -y python >/dev/null 2>&1 || return 1
  fi
}

if ensure_json_runtime; then
  if command -v node >/dev/null 2>&1; then
    node - "$CONFIG_ROOT" <<'NODE'
const fs = require("fs");
const path = require("path");
const root = process.argv[2];
const stamp = String(Date.now());
function load(p) {
  try {
    const d = JSON.parse(fs.readFileSync(p, "utf8"));
    return d && typeof d === "object" && !Array.isArray(d) ? d : {};
  } catch { return {}; }
}
function save(p, d) {
  fs.mkdirSync(path.dirname(p), { recursive: true });
  if (fs.existsSync(p)) fs.copyFileSync(p, `${p}.bak.${stamp}`);
  fs.writeFileSync(p, JSON.stringify(d, null, 2) + "\n", "utf8");
}
for (const app of ["xcode", "opencode"]) {
  const p = path.join(root, app, "tui.json");
  const c = load(p);
  if (!c.$schema) c.$schema = "https://opencode.ai/tui.json";
  c.mouse = true;
  c.scroll_speed = 5;
  c.scroll_acceleration = { enabled: true };
  save(p, c);
}
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);
NODE
  else
    PYBIN=$(command -v python3 || command -v python)
    "$PYBIN" - "$CONFIG_ROOT" <<'PY'
import json, os, shutil, sys, time
root = sys.argv[1]
stamp = time.time_ns()
def load(p):
    try:
        with open(p, "r", encoding="utf-8") as f:
            d = json.load(f)
        return d if isinstance(d, dict) else {}
    except Exception:
        return {}
def save(p, d):
    os.makedirs(os.path.dirname(p), exist_ok=True)
    if os.path.exists(p):
        shutil.copy2(p, f"{p}.bak.{stamp}")
    with open(p, "w", encoding="utf-8") as f:
        json.dump(d, f, ensure_ascii=False, indent=2)
        f.write("\n")
for app in ("xcode", "opencode"):
    p = os.path.join(root, app, "tui.json")
    c = load(p)
    c.setdefault("$schema", "https://opencode.ai/tui.json")
    c["mouse"] = True
    c["scroll_speed"] = 5
    c["scroll_acceleration"] = {"enabled": True}
    save(p, c)
p = os.path.join(root, "xcode", "cli.json")
c = load(p)
c.setdefault("$schema", "https://opencode.ai/v2/cli.json")
c["mouse"] = True
scroll = c.get("scroll")
if not isinstance(scroll, dict):
    scroll = {}
scroll["speed"] = 5
scroll["acceleration"] = True
c["scroll"] = scroll
save(p, c)
PY
  fi
  printf '        ✓ อัปเดต %s/xcode/{tui.json,cli.json} แล้ว\n' "$CONFIG_ROOT"
else
  printf '        ! ไม่พบ node/python ข้ามการ merge config\n' >&2
fi

# 4. Configure Termux extra-keys (if missing or not skipped)
echo "  [4/4] ตั้งค่าคีย์ลัด Termux (extra-keys)..."
if [ "$SKIP_EXTRA_KEYS" = 0 ]; then
  TERMUX_DIR="$HOME/.termux"
  TERMUX_PROP="$TERMUX_DIR/termux.properties"
  mkdir -p "$TERMUX_DIR"
  if [ -f "$TERMUX_PROP" ]; then
    if grep -q "extra-keys" "$TERMUX_PROP" 2>/dev/null; then
      printf '        • พบ extra-keys เดิมใน %s แล้ว (คงค่าเดิมไว้)\n' "$TERMUX_PROP"
    else
      cp -f "$TERMUX_PROP" "$TERMUX_PROP.bak.$(date +%s)"
      cat >>"$TERMUX_PROP" <<'PROP'

# xcode-mobile extra keys
extra-keys = [ \
  ['ESC', 'CTRL', 'ALT', 'TAB', 'KEYBOARD', '/', '-', '|'], \
  ['PGUP', 'PGDN', 'UP', 'DOWN', 'LEFT', 'RIGHT', 'HOME', 'END'] \
]
PROP
      printf '        ✓ เพิ่ม extra-keys ต่อท้าย %s แล้ว\n' "$TERMUX_PROP"
    fi
  else
    cat >"$TERMUX_PROP" <<'PROP'
### Termux Configuration for xcode Mobile
extra-keys = [ \
  ['ESC', 'CTRL', 'ALT', 'TAB', 'KEYBOARD', '/', '-', '|'], \
  ['PGUP', 'PGDN', 'UP', 'DOWN', 'LEFT', 'RIGHT', 'HOME', 'END'] \
]
terminal-cursor-style = block
terminal-cursor-blink-rate = 600
use-black-ui = true
terminal-transcript-rows = 5000
PROP
    printf '        ✓ สร้าง %s แล้ว\n' "$TERMUX_PROP"
  fi
  command -v termux-reload-settings >/dev/null 2>&1 && termux-reload-settings >/dev/null 2>&1 || true
fi

if command -v xcode >/dev/null 2>&1; then
  xcode reload >/dev/null 2>&1 || true
fi

printf '\n  \033[32m✓ ติดตั้ง xcode-mobile สำเร็จ!\033[0m\n\n'
printf '  • วิธีแสดงภาพคมชัด (Sixel): ดาวน์โหลด Termux Sixel APK ได้ที่\n'
printf '    %s\n' "$MOBILE_SITE"
printf '  • เริ่มใช้งาน: พิมพ์ \033[36mxcode\033[0m (ลากนิ้ว = เลื่อนแชท, แตะ = คลิก/โฟกัส)\n\n'
