#!/usr/bin/env python3
import json
import subprocess
import sys
from pathlib import Path

SKILL_SCRIPTS = Path(__file__).resolve().parent
PREPARE_SCRIPT = SKILL_SCRIPTS / 'prepare_playgrounds.py'
DEPLOY_SCRIPT = SKILL_SCRIPTS / 'deploy_to_workspace.py'


def fail(payload, code=1):
    print(json.dumps(payload, ensure_ascii=False))
    raise SystemExit(code)


def run_json(cmd):
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        fail({'ok': False, 'error': 'command_failed', 'command': cmd, 'details': result.stderr or result.stdout})
    try:
        return json.loads(result.stdout)
    except Exception:
        fail({'ok': False, 'error': 'invalid_json_output', 'command': cmd, 'output': result.stdout})


def main():
    if len(sys.argv) != 2:
        fail({'ok': False, 'error': 'usage', 'message': '用法: python3 scripts/run_playgrounds_flow.py <template_path>'})

    template_path = sys.argv[1]
    prepare = run_json(['python3', str(PREPARE_SCRIPT)])
    deploy = run_json(['python3', str(DEPLOY_SCRIPT), template_path, str(Path.home() / '.openclaw' / 'workspace-playgrounds'), '--with-tui'])

    print(json.dumps({
        'ok': True,
        'mode': 'A+B+C',
        'prepare': prepare,
        'deploy': deploy,
    }, ensure_ascii=False))


if __name__ == '__main__':
    main()
