#!/usr/bin/env python3
"""
adobe-host: 容器内高效驱动 macOS 宿主机 Premiere Pro / After Effects / Media Encoder 的桥接 CLI
支持：
  adobe-host to-host-path <path>               # 容器路径 (/data, /host) -> 宿主机绝对路径 (/Users/...)
  adobe-host status                            # 1秒内探测 18999 MCP 桥、PR/AE/ME 进程与已打开工程状态
  adobe-host warmup [project.prproj]           # 自动唤醒宿主机 PR + ME 并配置 AE 脚本写入权限与免欢迎页
  adobe-host aerender -project ... -comp ... -output ... [-OMtemplate ...] # 跨容器直接调用宿主机 aerender 无头极速渲染
  adobe-host pipeline --spec <spec.json> [--tag r1]                        # 跨容器调用宿主机 Hermes 一键成片管线
"""
import json, os, subprocess, sys, urllib.request

H_USER = os.environ.get("HOST_USER", "xwxie")
H_HOME = os.environ.get("HOST_HOME", f"/Users/{H_USER}")
if H_HOME == "/root":
    H_HOME = f"/Users/{H_USER}"
H_PWD = os.environ.get("HOST_PWD", f"{H_HOME}/Public/jimi-pro")
if H_PWD == "/app":
    H_PWD = f"{H_HOME}/Public/jimi-pro"

def to_host_path(p: str) -> str:
    if not p:
        return p
    p = os.path.abspath(p) if p.startswith(("/data", "/host", "/root/.openclaw")) else p
    if p.startswith("/data/"):
        return f"{H_PWD}/Materials/" + p[len("/data/"):]
    if p == "/data":
        return f"{H_PWD}/Materials"
    if p.startswith("/host/"):
        return f"{H_HOME}/" + p[len("/host/"):]
    if p == "/host":
        return H_HOME
    if p.startswith("/root/.openclaw/"):
        return f"{H_PWD}/.openclaw/" + p[len("/root/.openclaw/"):]
    return p

def ssh_run(cmd: str, timeout: int = 300):
    full = [
        "ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no",
        "-o", "ConnectTimeout=4", f"{H_USER}@host.docker.internal",
        f"export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH; {cmd}"
    ]
    return subprocess.run(full, capture_output=True, text=True, timeout=timeout)

def check_status():
    info = {"mcp_http": False, "pr_running": False, "ae_running": False, "me_running": False, "ssh_ok": False}
    try:
        with urllib.request.urlopen("http://host.docker.internal:18999/health", timeout=2.5) as resp:
            data = json.loads(resp.read().decode("utf-8", errors="replace"))
            info["mcp_http"] = (data.get("status") == "ok")
            info["mcp_detail"] = data
    except Exception as e:
        info["mcp_error"] = str(e)

    r = ssh_run(
        "ps aux | grep -E 'Adobe Premiere Pro|After Effects|Adobe Media Encoder|premiere-pro-mcp' | grep -v grep; "
        "echo '---HEARTBEAT---'; "
        "find /tmp /var/folders -name 'bridge-heartbeat.json' 2>/dev/null | head -3 | xargs head -c 500 2>/dev/null || true",
        timeout=8
    )
    if r.returncode == 0:
        info["ssh_ok"] = True
        out = r.stdout
        info["pr_running"] = ("Adobe Premiere Pro" in out)
        info["ae_running"] = ("After Effects" in out)
        info["me_running"] = ("Adobe Media Encoder" in out)
        info["processes_raw"] = [l.strip() for l in out.split("---HEARTBEAT---")[0].splitlines() if l.strip()]
        if "---HEARTBEAT---" in out:
            hb = out.split("---HEARTBEAT---", 1)[1].strip()
            if hb:
                info["heartbeat"] = hb
    else:
        info["ssh_error"] = (r.stderr or r.stdout).strip()
    print(json.dumps(info, ensure_ascii=False, indent=2))

def warmup(prproj=None):
    ae_pref_cmd = r'''
for f in "$HOME/Library/Preferences/Adobe/After Effects"/*/Adobe\ After\ Effects*\ 设置.txt "$HOME/Library/Preferences/Adobe/After Effects"/*/Adobe\ After\ Effects*\ Prefs*.txt; do
  [ -f "$f" ] || continue
  python3 - "$f" << 'PY'
import sys
p = sys.argv[1]
txt = open(p, encoding="utf-8", errors="ignore").read()
changed = False
if '"Pref_SCRIPTING_FILE_NETWORK_SECURITY" = "0"' in txt:
    txt = txt.replace('"Pref_SCRIPTING_FILE_NETWORK_SECURITY" = "0"', '"Pref_SCRIPTING_FILE_NETWORK_SECURITY" = "1"')
    changed = True
if '"Show Welcome Screen" = 01' in txt:
    txt = txt.replace('"Show Welcome Screen" = 01', '"Show Welcome Screen" = 00')
    changed = True
if changed:
    open(p, "w", encoding="utf-8").write(txt)
    print("Patched AE prefs:", p)
PY
done
'''
    ssh_run(ae_pref_cmd, timeout=15)
    host_proj = to_host_path(prproj) if prproj else ""
    open_cmd = 'open -g -a "Adobe Media Encoder 2024" 2>/dev/null || open -g -a "Adobe Media Encoder 2025" 2>/dev/null || true; '
    if host_proj:
        open_cmd += f'open -a "Adobe Premiere Pro 2024" "{host_proj}" 2>/dev/null || open -a "Adobe Premiere Pro 2025" "{host_proj}" 2>/dev/null || true'
    else:
        open_cmd += 'open -a "Adobe Premiere Pro 2024" 2>/dev/null || open -a "Adobe Premiere Pro 2025" 2>/dev/null || true'
    r = ssh_run(open_cmd, timeout=15)
    print("Warmup executed, returncode=", r.returncode)
    check_status()

def run_aerender(args):
    translated = []
    i = 0
    while i < len(args):
        a = args[i]
        if a in ("-project", "-output") and i + 1 < len(args):
            translated.extend([a, f'"{to_host_path(args[i+1])}"'])
            i += 2
        elif a in ("-comp", "-OMtemplate", "-RStemplate") and i + 1 < len(args):
            translated.extend([a, f'"{args[i+1]}"'])
            i += 2
        else:
            translated.append(a)
            i += 1
    cmd = (
        'AER="/Applications/Adobe After Effects 2024/aerender"; '
        '[ -x "$AER" ] || AER="/Applications/Adobe After Effects 2025/aerender"; '
        f'"$AER" {" ".join(translated)}'
    )
    r = ssh_run(cmd, timeout=600)
    sys.stdout.write(r.stdout)
    sys.stderr.write(r.stderr)
    sys.exit(r.returncode)

def run_pipeline(args):
    translated = []
    i = 0
    while i < len(args):
        a = args[i]
        if a == "--spec" and i + 1 < len(args):
            translated.extend(["--spec", f'"{to_host_path(args[i+1])}"'])
            i += 2
        else:
            translated.append(a)
            i += 1
    cmd = f'~/.hermes/hermes-agent/venv/bin/python ~/.hermes/tools/video-pipeline/pipeline.py {" ".join(translated)}'
    r = ssh_run(cmd, timeout=900)
    sys.stdout.write(r.stdout)
    sys.stderr.write(r.stderr)
    sys.exit(r.returncode)

if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
        print(__doc__.strip())
        sys.exit(0)
    sub = sys.argv[1]
    if sub == "to-host-path":
        print(to_host_path(sys.argv[2] if len(sys.argv) > 2 else ""))
    elif sub == "status":
        check_status()
    elif sub == "warmup":
        warmup(sys.argv[2] if len(sys.argv) > 2 else None)
    elif sub == "aerender":
        run_aerender(sys.argv[2:])
    elif sub == "pipeline":
        run_pipeline(sys.argv[2:])
    else:
        print(f"Unknown subcommand: {sub}", file=sys.stderr)
        sys.exit(1)
