"""Account and utility tools for MTurk."""

import json
from mcp.types import TextContent

from ..client import get_mturk_client, format_error, is_sandbox


def register_tools(register):
    """Register account-related tools."""

    async def get_account_balance(args: dict) -> list[TextContent]:
        """Get the available balance in your MTurk requester account."""
        try:
            client = get_mturk_client()
            response = client.get_account_balance()
            result = {
                "available_balance": response["AvailableBalance"],
                "on_hold_balance": response.get("OnHoldBalance"),
                "environment": "sandbox" if is_sandbox() else "production",
            }
            return [TextContent(type="text", text=json.dumps(result, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "get_account_balance",
        """Retrieves the current available balance in your Amazon Mechanical Turk requester account.

Use this tool to check how much money you have available before creating HITs, or to verify funds after making payments. The balance is returned in USD.

Returns two values:
- available_balance: Money you can spend on HITs and bonuses right now
- on_hold_balance: Money reserved for pending assignments (will be released when you approve/reject work)

Also indicates whether you're connected to the sandbox (testing) or production environment. In sandbox mode, the balance is fake money for testing purposes.

This tool takes no parameters and should be called whenever you need to verify you have sufficient funds for an operation.""",
        {"type": "object", "properties": {}, "required": []},
        get_account_balance,
    )

    async def list_reviewable_hits(args: dict) -> list[TextContent]:
        """List HITs that have assignments ready for review."""
        try:
            client = get_mturk_client()
            params = {
                "Status": args.get("status", "Reviewable"),
                "MaxResults": min(args.get("max_results", 100), 100),
            }
            if args.get("hit_type_id"):
                params["HITTypeId"] = args["hit_type_id"]

            response = client.list_reviewable_hits(**params)
            hits = response.get("HITs", [])
            result = {
                "count": len(hits),
                "hits": [
                    {
                        "hit_id": hit["HITId"],
                        "hit_type_id": hit.get("HITTypeId"),
                        "title": hit.get("Title"),
                        "creation_time": str(hit.get("CreationTime")),
                    }
                    for hit in hits
                ],
            }
            return [TextContent(type="text", text=json.dumps(result, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "list_reviewable_hits",
        """Finds HITs that have worker submissions waiting to be reviewed (approved or rejected).

Use this tool when you want to check if any workers have completed assignments that need your attention. This is typically the first step in the review workflow - call this to find HITs with pending work, then use list_assignments to see the actual submissions.

A HIT becomes 'Reviewable' when at least one worker has submitted an assignment that hasn't been approved or rejected yet. Once all assignments for a HIT are reviewed, it moves out of the reviewable state.

The status parameter filters results:
- 'Reviewable' (default): HITs with at least one submitted assignment awaiting review
- 'Reviewing': HITs you've marked as being actively reviewed (rarely used)

Returns basic HIT info including hit_id (needed for list_assignments), title, and creation time. Does not return the actual worker submissions - use list_assignments for that.""",
        {
            "type": "object",
            "properties": {
                "hit_type_id": {
                    "type": "string",
                    "description": "Optional filter to only show HITs of a specific type. HIT types group HITs with the same reward, duration, and qualifications. Omit to see all reviewable HITs."
                },
                "status": {
                    "type": "string",
                    "enum": ["Reviewable", "Reviewing"],
                    "description": "Filter by review status. 'Reviewable' (default) shows HITs with pending submissions. 'Reviewing' shows HITs marked as being actively reviewed.",
                    "default": "Reviewable"
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of HITs to return, between 1 and 100. Defaults to 100. Use smaller values for faster responses when you only need a few results.",
                    "default": 100,
                    "minimum": 1,
                    "maximum": 100
                },
            },
            "required": [],
        },
        list_reviewable_hits,
    )
