#!/usr/bin/env python3
# 中文注释：
# 文件：echobot/skills/siyuan/scripts/runner.py
# 说明：SiYuan Skill 的命令行执行入口，供 run_skill_script 调用。
"""
SiYuan Skill Runner

Usage:
  python runner.py <tool_name> [json_arguments]

Examples:
  python runner.py siyuan_get_notebooks
  python runner.py siyuan_search '{"query":"AI", "limit":10}'
"""

from __future__ import annotations

import json
import sys

try:
    from .tools import SiYuanTools
except ImportError:  # pragma: no cover - allow direct script execution
    from tools import SiYuanTools


def execute_tool(tool_name: str, arguments: dict) -> str:
    """Execute a SiYuan tool with structured arguments."""
    tools = SiYuanTools()

    if tool_name == "siyuan_search":
        return tools.search_notes(
            query=arguments.get("query", ""),
            limit=arguments.get("limit", 20),
            type=arguments.get("type", "blocks"),
        )
    if tool_name == "siyuan_get_notebooks":
        return tools.get_notebooks()
    if tool_name == "siyuan_get_recent_docs":
        return tools.get_recent_docs(limit=arguments.get("limit", 10))
    if tool_name == "siyuan_get_dailies":
        return tools.get_daily_notes(
            start_date=arguments.get("start_date", ""),
            end_date=arguments.get("end_date", ""),
        )
    if tool_name == "siyuan_get_document":
        return tools.get_document(doc_id=arguments.get("doc_id", ""))
    if tool_name == "siyuan_create_document":
        return tools.create_document(
            notebook_id=arguments.get("notebook_id", ""),
            path=arguments.get("path", ""),
            title=arguments.get("title", ""),
            content=arguments.get("content", ""),
        )
    if tool_name == "siyuan_update_document":
        return tools.update_document(
            doc_id=arguments.get("doc_id", ""),
            content=arguments.get("content", ""),
        )
    if tool_name == "siyuan_query_sql":
        return tools.query_database(sql=arguments.get("sql", ""))
    if tool_name == "siyuan_query_blocks":
        return tools.query_blocks_hsql(
            hsql=arguments.get("hsql", ""),
            limit=arguments.get("limit", 100),
        )
    return f"Unknown tool: {tool_name}"


def _usage() -> str:
    return (
        "Usage: python runner.py <tool_name> [json_arguments]\n"
        "Example: python runner.py siyuan_search "
        "'{\"query\":\"AI\",\"limit\":10}'"
    )


def main() -> int:
    if len(sys.argv) < 2:
        print(_usage(), file=sys.stderr)
        return 2

    tool_name = str(sys.argv[1] or "").strip()
    if not tool_name:
        print("Error: tool_name cannot be empty.", file=sys.stderr)
        print(_usage(), file=sys.stderr)
        return 2

    raw_args = sys.argv[2] if len(sys.argv) > 2 else "{}"
    try:
        arguments = json.loads(raw_args)
    except json.JSONDecodeError as exc:
        print(f"Error: invalid JSON arguments: {exc}", file=sys.stderr)
        return 2

    if not isinstance(arguments, dict):
        print("Error: json_arguments must be a JSON object.", file=sys.stderr)
        return 2

    try:
        output = execute_tool(tool_name, arguments)
    except Exception as exc:
        print(f"Error running tool: {exc}", file=sys.stderr)
        return 1

    print(output)
    return 0


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