#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path

TOOL_ID = 'agent-core-1688-sourcing'
SKILL_ID = 'selection-art-workflow'
DEFAULT_ENTRYPOINT = 'examples/1688_script.py'
PERMISSION = 'locked_until_authorized'
LOCKED_ENTRYPOINTS = ['references/fixed-script.py']


def find_package_root() -> Path:
    here = Path(__file__).resolve()
    for parent in here.parents:
        if (parent / "manifest.json").exists() and (parent / "runtime-tools" / TOOL_ID).exists():
            return parent
    raise SystemExit(json.dumps({"ok": False, "error": "AIOS package root not found", "tool": TOOL_ID}, ensure_ascii=False))


def main() -> int:
    parser = argparse.ArgumentParser(description="Run AIOS runtime tool wrapper.")
    parser.add_argument("--entrypoint", default=DEFAULT_ENTRYPOINT, help="tool-relative script entrypoint")
    parser.add_argument("args", nargs=argparse.REMAINDER)
    parsed = parser.parse_args()
    entrypoint = parsed.entrypoint.strip()
    passthrough = parsed.args
    if passthrough and passthrough[0] == "--":
        passthrough = passthrough[1:]

    root = find_package_root()
    tool_root = root / "runtime-tools" / TOOL_ID
    if PERMISSION == "locked_until_authorized" or (PERMISSION == "mixed" and os.environ.get("AIOS_ALLOW_LOCKED_TOOL") != "1" and entrypoint in LOCKED_ENTRYPOINTS):
        print(json.dumps({
            "ok": False,
            "status": "locked_until_authorized",
            "skill": SKILL_ID,
            "tool": TOOL_ID,
            "message": "该工具涉及授权或高风险动作，需客户/负责人确认后设置 AIOS_ALLOW_LOCKED_TOOL=1 再运行。",
        }, ensure_ascii=False))
        return 2
    target = tool_root / entrypoint
    if not entrypoint or not target.exists():
        print(json.dumps({
            "ok": True,
            "status": "reference_only",
            "skill": SKILL_ID,
            "tool": TOOL_ID,
            "tool_root": str(tool_root),
        }, ensure_ascii=False))
        return 0
    if target.suffix == ".py":
        cmd = [sys.executable, str(target), *passthrough]
    elif target.suffix == ".sh":
        cmd = ["/bin/bash", str(target), *passthrough]
    elif target.suffix == ".ps1":
        cmd = ["pwsh", str(target), *passthrough]
    elif target.suffix == ".js":
        print(json.dumps({
            "ok": True,
            "status": "asset_ready",
            "skill": SKILL_ID,
            "tool": TOOL_ID,
            "asset": str(target),
        }, ensure_ascii=False))
        return 0
    else:
        print(json.dumps({
            "ok": True,
            "status": "asset_ready",
            "skill": SKILL_ID,
            "tool": TOOL_ID,
            "asset": str(target),
        }, ensure_ascii=False))
        return 0
    return subprocess.call(cmd)


if __name__ == "__main__":
    raise SystemExit(main())
