"""Job status checking tool for Influ2 MCP."""

from __future__ import annotations

import json
from typing import Annotated

from influ2_mcp.client import get_api_client
from influ2_mcp.errors import Influ2Error, format_error_for_llm
from influ2_mcp.server import mcp


@mcp.tool()
async def influ2_check_job(
    job_id: Annotated[
        str,
        "The job ID returned by a previous async operation (cohort creation, target management)",
    ],
) -> str:
    """Check the status of an async operation (cohort creation, target management).

    Returns the job status: pending, processing, completed, or failed, along with
    any progress details and error messages. Use this only if a compound tool
    (influ2_create_cohort or influ2_manage_targets) timed out and returned a job_id
    instead of a completed result.

    Most users will never need this tool directly — the compound tools poll
    automatically. Use it when:
    - A previous operation timed out and gave you a job_id
    - You want to manually monitor a long-running operation
    - You need to check if a large target sync (1000+ targets) has finished

    When a user asks: "Is my upload done?", "Check the job status",
    "Has the target sync finished?", "What happened with my cohort creation?",
    "My operation timed out — check if it completed"
    """
    try:
        api_client = get_api_client()
        response = await api_client.get(f"/public/v1/jobs/{job_id}")

        status = response.get("status", "unknown")
        result = {
            "job": response,
            "status_summary": status,
        }

        if status in ("completed", "done", "finished"):
            result["_note"] = "Operation completed successfully."
        elif status in ("failed", "error"):
            result["_note"] = (
                "Operation failed. Check the error details above. "
                "You may need to retry the operation."
            )
        elif status in ("pending", "processing", "in_progress"):
            result["_note"] = (
                "Operation still in progress. Check again in a few seconds "
                "with influ2_check_job(job_id='...')."
            )

        return json.dumps(result, indent=2, default=str)

    except Influ2Error as e:
        return json.dumps(format_error_for_llm(e))
    except Exception as e:
        return json.dumps(format_error_for_llm(e))
