#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""檢查或執行可選的 browse.sh CLI。"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from services.browse_sh_tool import BrowseShTool  # noqa: E402


def main() -> int:
    parser = argparse.ArgumentParser(description="檢查 browse.sh CLI，或執行一次診斷命令。")
    parser.add_argument("--cli", help="browse CLI 路徑；預設使用 BROWSE_SH_CLI 或 PATH。")
    parser.add_argument("--timeout", type=int, default=90, help="執行逾時秒數。")
    parser.add_argument(
        "browse_args",
        nargs=argparse.REMAINDER,
        help="要傳給 browse 的參數；未提供時只輸出 availability。",
    )
    args = parser.parse_args()

    tool = BrowseShTool(cli_path=args.cli, timeout_seconds=args.timeout)
    if not args.browse_args:
        print(json.dumps(tool.availability().as_dict(), ensure_ascii=False, indent=2))
        return 0

    browse_args = tuple(arg for arg in args.browse_args if arg != "--")
    result = tool.run(browse_args, timeout_seconds=args.timeout)
    print(json.dumps(result.as_dict(), ensure_ascii=False, indent=2))
    return 0 if result.ok else 1


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