"""定时任务/系统作业工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient




def get_jobs_tools() -> list[Tool]:
    """获取 Jobs 相关工具"""
    return [
        Tool(
            name="jobs.list",
            description="列出所有作业",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
        Tool(
            name="jobs.run_now",
            description="立即运行作业",
            inputSchema={
                "type": "object",
                "properties": {
                    "id": {"type": "string", "description": "作业 ID"},
                },
                "required": ["id"],
            },
        ),
        Tool(
            name="jobs.history",
            description="获取作业运行历史",
            inputSchema={
                "type": "object",
                "properties": {
                    "id": {"type": "string", "description": "作业 ID"},
                    "limit": {"type": "integer", "description": "返回数量限制"},
                    "before": {"type": "string", "description": "在此之前的时间戳"},
                },
                "required": ["id"],
            },
        ),
    ]


async def handle_jobs_list(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 jobs.list 工具调用"""
    try:
        result = client.http.get("/api/_admin/jobs")
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({"error": str(e)}, ensure_ascii=False)
        )]


async def handle_jobs_run_now(
    client: TrailBaseClient,
    id: str,
) -> list[TextContent]:
    """处理 jobs.run_now 工具调用"""
    try:
        # 将字符串 ID 转换为整数（TrailBase API 期望整数 ID）
        try:
            job_id = int(id)
        except ValueError:
            return [TextContent(
                type="text",
                text=json.dumps({
                    "error": "Invalid job ID",
                    "message": f"Job ID must be an integer, got: {id}"
                }, ensure_ascii=False)
            )]
        
        result = client.http.post("/api/_admin/job/run", json={"id": job_id})
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({"error": str(e)}, ensure_ascii=False)
        )]


async def _update_job_config(
    client: TrailBaseClient,
    job_id: str,
    schedule: str | None = None,
    disabled: bool | None = None,
) -> list[TextContent]:
    """通过配置 API 更新作业配置的辅助函数"""
    try:
        # 先获取作业列表，验证作业 ID 是否存在并获取作业信息
        try:
            jobs_result = client.http.get("/api/_admin/jobs")
            jobs = jobs_result.get("jobs", [])
            job = next((j for j in jobs if str(j.get("id")) == str(job_id)), None)
            
            if not job:
                return [TextContent(
                    type="text",
                    text=json.dumps({
                        "error": "JobNotFound",
                        "message": f"作业 ID {job_id} 不存在",
                        "available_jobs": [{"id": j.get("id"), "name": j.get("name")} for j in jobs],
                    }, ensure_ascii=False)
                )]
            
            job_name = job.get("name", f"Job_{job_id}")
        except Exception as e:
            # 如果无法获取作业列表，使用作业 ID 作为名称
            job_name = f"Job_{job_id}"
        
        # 构建配置示例（使用作业 ID 数字，因为配置文件中使用枚举值）
        try:
            job_system_id = int(job_id)
        except ValueError:
            return [TextContent(
                type="text",
                text=json.dumps({
                    "error": "InvalidJobID",
                    "message": f"无效的作业 ID: {job_id}。作业 ID 必须是数字。",
                }, ensure_ascii=False)
            )]
        
        # 构建配置示例（使用数字 ID，TrailBase 会自动映射到对应的枚举值）
        config_example_parts = [f"id: {job_system_id}"]
        if schedule is not None:
            config_example_parts.append(f'schedule: "{schedule}"')
        if disabled is not None:
            config_example_parts.append(f"disabled: {str(disabled).lower()}")
        
        config_example = "jobs {\n  system_jobs: [\n    {\n      " + "\n      ".join(config_example_parts) + "\n    }\n  ]\n}"
        
        # TrailBase 配置 API 使用 protobuf 格式，需要通过编辑配置文件来实现
        return [TextContent(
            type="text",
            text=json.dumps({
                "error": "NotImplemented",
                "message": "作业配置需要通过编辑配置文件来实现",
                "config_file": "traildepot/config.textproto",
                "config_example": config_example,
                "job_id": job_id,
                "job_name": job_name,
            }, ensure_ascii=False)
        )]
        
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({"error": str(e)}, ensure_ascii=False)
        )]


async def handle_jobs_update_schedule(
    client: TrailBaseClient,
    id: str,
    schedule: str,
) -> list[TextContent]:
    """处理 jobs.update_schedule 工具调用"""
    return await _update_job_config(client, id, schedule=schedule)


async def handle_jobs_enable(
    client: TrailBaseClient,
    id: str,
) -> list[TextContent]:
    """处理 jobs.enable 工具调用"""
    return await _update_job_config(client, id, disabled=False)


async def handle_jobs_disable(
    client: TrailBaseClient,
    id: str,
) -> list[TextContent]:
    """处理 jobs.disable 工具调用"""
    return await _update_job_config(client, id, disabled=True)


async def handle_jobs_history(
    client: TrailBaseClient,
    id: str,
    limit: int | None = None,
    before: str | None = None,
) -> list[TextContent]:
    """处理 jobs.history 工具调用"""
    try:
        # TrailBase 没有直接的 jobs history API
        # 但可以通过 logs API 查询 job 相关的日志
        # 首先获取 job 信息以确定 job 名称
        jobs_result = client.http.get("api/_admin/jobs")
        jobs = jobs_result.get("jobs", [])
        job = next((j for j in jobs if str(j.get("id")) == str(id)), None)
        
        if not job:
            return [TextContent(
                type="text",
                text=json.dumps({"error": f"Job with id {id} not found"}, ensure_ascii=False)
            )]
        
        job_name = job.get("name", "")
        
        # 通过 logs API 查询该 job 的执行日志
        # 注意：这需要 logs 中有 job 相关的记录
        params: dict[str, Any] = {}
        if limit:
            params["limit"] = limit
        if before:
            params["cursor"] = before
        
        # 尝试过滤 job 相关的日志（URL 中包含 job 名称）
        # 注意：这取决于 TrailBase 如何记录 job 执行日志
        logs_result = client.http.get("api/_admin/logs", params=params)
        
        # 过滤包含 job 名称的日志条目
        entries = logs_result.get("entries", [])
        job_logs = [
            entry for entry in entries
            if job_name.lower() in entry.get("url", "").lower() or 
               job_name.lower() in entry.get("method", "").lower()
        ]
        
        return [TextContent(
            type="text",
            text=json.dumps({
                "job_id": id,
                "job_name": job_name,
                "history": job_logs[:limit] if limit else job_logs,
                "note": "Job history is derived from logs. For detailed history, use logs.query with appropriate filters."
            }, ensure_ascii=False)
        )]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({"error": str(e)}, ensure_ascii=False)
        )]

