"""Worker management tools for blocking, notifying, and paying bonuses."""

import json
from mcp.types import TextContent

from ..client import get_mturk_client, format_error


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

    async def block_worker(args: dict) -> list[TextContent]:
        """Block a worker from accepting your HITs."""
        try:
            client = get_mturk_client()
            client.create_worker_block(
                WorkerId=args["worker_id"],
                Reason=args["reason"],
            )
            return [TextContent(type="text", text=json.dumps({
                "success": True,
                "worker_id": args["worker_id"],
                "action": "blocked",
                "reason": args["reason"],
            }, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "block_worker",
        """Prevents a worker from seeing or accepting any of your HITs in the future.

Use this tool as a last resort for workers who:
- Consistently submit spam or gibberish
- Appear to be bots or automated systems
- Violate your task guidelines repeatedly despite feedback
- Exhibit clearly bad-faith behavior

IMPORTANT CONSIDERATIONS:
- Blocking is account-wide - the worker can't do ANY of your HITs, not just the problematic one
- The worker is NOT notified they're blocked - they simply won't see your HITs
- The reason you provide is for YOUR records only (worker doesn't see it)
- Consider using qualification-based exclusion instead for less severe cases

Blocking is more severe than rejection. Rejection affects one assignment; blocking affects all future interactions. Use rejection + feedback first to give workers a chance to improve.

To reverse a block, use unblock_worker. You can see all blocked workers with list_blocked_workers.""",
        {
            "type": "object",
            "properties": {
                "worker_id": {
                    "type": "string",
                    "description": "The worker ID to block. Get this from list_assignments. Once blocked, this worker cannot see or accept any of your HITs."
                },
                "reason": {
                    "type": "string",
                    "description": "Your internal note explaining why you blocked this worker. The worker does NOT see this. Keep it factual for your records. Example: 'Submitted random characters on 5 consecutive assignments'"
                },
            },
            "required": ["worker_id", "reason"],
        },
        block_worker,
    )

    async def unblock_worker(args: dict) -> list[TextContent]:
        """Remove a block from a worker, allowing them to work on your HITs again."""
        try:
            client = get_mturk_client()
            params = {"WorkerId": args["worker_id"]}
            if args.get("reason"):
                params["Reason"] = args["reason"]

            client.delete_worker_block(**params)
            return [TextContent(type="text", text=json.dumps({
                "success": True,
                "worker_id": args["worker_id"],
                "action": "unblocked",
            }, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "unblock_worker",
        """Removes a block from a worker, allowing them to see and accept your HITs again.

Use this tool when:
- You blocked a worker by mistake
- A worker reached out and explained their situation
- Enough time has passed that you want to give them another chance
- You're cleaning up old blocks that are no longer relevant

The worker is not notified when unblocked - they'll simply start seeing your HITs again.

To find workers you've blocked, use list_blocked_workers. The reason field is optional and for your records only.""",
        {
            "type": "object",
            "properties": {
                "worker_id": {
                    "type": "string",
                    "description": "The worker ID to unblock. Get this from list_blocked_workers."
                },
                "reason": {
                    "type": "string",
                    "description": "Optional note for your records about why you're unblocking. Example: 'Worker apologized and promised to follow guidelines'"
                },
            },
            "required": ["worker_id"],
        },
        unblock_worker,
    )

    async def list_blocked_workers(args: dict) -> list[TextContent]:
        """List all workers you have blocked."""
        try:
            client = get_mturk_client()
            response = client.list_worker_blocks(MaxResults=min(args.get("max_results", 100), 100))
            blocks = response.get("WorkerBlocks", [])
            result = {
                "count": len(blocks),
                "blocked_workers": [
                    {
                        "worker_id": b["WorkerId"],
                        "reason": b.get("Reason"),
                    }
                    for b in blocks
                ],
            }
            return [TextContent(type="text", text=json.dumps(result, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "list_blocked_workers",
        """Returns a list of all workers you have blocked from your HITs.

Use this tool to:
- Review who you've blocked and why (the reason you provided when blocking)
- Find worker IDs for workers you want to unblock
- Audit your blocklist periodically to clean up old blocks

Each entry shows the worker_id and the reason you recorded when blocking them.

Note: Only returns up to 100 blocked workers. If you have more, you may need to paginate or clean up old blocks.""",
        {
            "type": "object",
            "properties": {
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of blocked workers to return, between 1 and 100. Defaults to 100.",
                    "default": 100,
                    "minimum": 1,
                    "maximum": 100
                },
            },
            "required": [],
        },
        list_blocked_workers,
    )

    async def notify_workers(args: dict) -> list[TextContent]:
        """Send an email notification to one or more workers."""
        try:
            client = get_mturk_client()
            worker_list = [w.strip() for w in args["worker_ids"].split(",")]

            client.notify_workers(
                Subject=args["subject"],
                MessageText=args["message"],
                WorkerIds=worker_list,
            )
            return [TextContent(type="text", text=json.dumps({
                "success": True,
                "workers_notified": worker_list,
                "subject": args["subject"],
            }, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "notify_workers",
        """Sends an email message to one or more workers through MTurk's messaging system.

Use this tool to:
- Thank workers for excellent work
- Invite trusted workers to new HITs
- Clarify task instructions if many workers are confused
- Apologize for issues with your HITs
- Request workers return for follow-up studies

IMPORTANT GUIDELINES:
- Workers can block requesters who send too many messages - use sparingly
- Messages come from your MTurk requester account, not a personal email
- Keep messages professional and relevant to work
- Don't use for marketing unrelated to your HITs

The message goes to workers' MTurk-associated email addresses. They may have filters or not check frequently, so don't rely on immediate responses.

Subject lines should be clear and professional. Messages should be concise and actionable.

Example use: After a successful survey, message participants: "Thank you for completing our research survey. We've posted a follow-up study you may be interested in." """,
        {
            "type": "object",
            "properties": {
                "worker_ids": {
                    "type": "string",
                    "description": "Comma-separated list of worker IDs to message. Example: 'A1B2C3D4E5,F6G7H8I9J0'. Get worker IDs from list_assignments. Maximum varies but keep it reasonable (under 100)."
                },
                "subject": {
                    "type": "string",
                    "description": "Email subject line. Keep it professional and clear. Example: 'Thank you for your survey response' or 'New HIT available that may interest you'"
                },
                "message": {
                    "type": "string",
                    "description": "The message body. Keep it concise and relevant to their work. Include any action items clearly. Be professional - this reflects on you as a requester."
                },
            },
            "required": ["worker_ids", "subject", "message"],
        },
        notify_workers,
    )

    async def send_bonus(args: dict) -> list[TextContent]:
        """Send a bonus payment to a worker for a specific assignment."""
        try:
            client = get_mturk_client()
            client.send_bonus(
                WorkerId=args["worker_id"],
                AssignmentId=args["assignment_id"],
                BonusAmount=args["bonus_amount"],
                Reason=args["reason"],
            )
            return [TextContent(type="text", text=json.dumps({
                "success": True,
                "worker_id": args["worker_id"],
                "assignment_id": args["assignment_id"],
                "bonus_amount": args["bonus_amount"],
                "reason": args["reason"],
            }, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "send_bonus",
        """Sends an additional payment (bonus) to a worker for a specific assignment they completed.

Use this tool to:
- Reward exceptionally high-quality work
- Compensate workers for extra effort or time
- Pay for legitimate work on a HIT you had to reject for technical reasons
- Incentivize workers in longitudinal studies
- Make up for your own mistakes (e.g., unclear instructions that caused rework)

IMPORTANT:
- Bonuses cost real money - they're charged to your account immediately
- MTurk charges fees on bonuses (typically 20%)
- Workers LOVE bonuses - they're great for building a reliable workforce
- The reason you provide IS shown to the worker

Bonuses must be tied to a specific assignment (you can't bonus someone randomly). The assignment must be approved or rejected already - you can't bonus pending work.

Good bonus practices:
- Be specific about why: "Bonus for providing detailed explanations" not just "Good work"
- Fair bonuses for extra work build trust and encourage quality
- Even small bonuses ($0.10-0.25) are appreciated and remembered""",
        {
            "type": "object",
            "properties": {
                "worker_id": {
                    "type": "string",
                    "description": "The worker ID to send the bonus to. Must match the worker who completed the assignment."
                },
                "assignment_id": {
                    "type": "string",
                    "description": "The assignment ID this bonus is for. The assignment must exist and be completed (approved or rejected). Get from list_assignments."
                },
                "bonus_amount": {
                    "type": "string",
                    "description": "Bonus amount in USD as a string. Example: '0.50' for 50 cents, '2.00' for $2.00. Must be at least $0.01. You'll also pay MTurk fees on top of this."
                },
                "reason": {
                    "type": "string",
                    "description": "Message explaining why you're giving this bonus. THE WORKER SEES THIS. Be specific and appreciative. Example: 'Thank you for providing such detailed and thoughtful responses!'"
                },
            },
            "required": ["worker_id", "assignment_id", "bonus_amount", "reason"],
        },
        send_bonus,
    )

    async def list_bonus_payments(args: dict) -> list[TextContent]:
        """List bonus payments made. Must specify either hit_id or assignment_id."""
        try:
            if not args.get("hit_id") and not args.get("assignment_id"):
                return [TextContent(type="text", text="Error: Must specify either hit_id or assignment_id")]

            client = get_mturk_client()
            params = {"MaxResults": min(args.get("max_results", 100), 100)}
            if args.get("hit_id"):
                params["HITId"] = args["hit_id"]
            if args.get("assignment_id"):
                params["AssignmentId"] = args["assignment_id"]

            response = client.list_bonus_payments(**params)
            payments = response.get("BonusPayments", [])
            result = {
                "count": len(payments),
                "bonus_payments": [
                    {
                        "worker_id": p["WorkerId"],
                        "assignment_id": p["AssignmentId"],
                        "bonus_amount": p["BonusAmount"],
                        "reason": p.get("Reason"),
                        "grant_time": str(p.get("GrantTime")),
                    }
                    for p in payments
                ],
            }
            return [TextContent(type="text", text=json.dumps(result, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "list_bonus_payments",
        """Lists bonus payments you've made, filtered by HIT or assignment.

Use this tool to:
- Audit bonus spending on a specific HIT
- Verify a bonus was sent successfully
- Track how much you've bonused across a project
- Ensure you haven't accidentally double-bonused a worker

You MUST provide either a hit_id (to see all bonuses for that HIT) or an assignment_id (to see bonuses for that specific assignment). Cannot list all bonuses across your entire account.

Returns the amount, worker, assignment, reason, and timestamp for each bonus payment.

Note: This shows bonuses YOU sent. It doesn't show the base HIT payment, only additional bonuses.""",
        {
            "type": "object",
            "properties": {
                "hit_id": {
                    "type": "string",
                    "description": "List bonuses for all assignments in this HIT. Provide either this OR assignment_id, not both."
                },
                "assignment_id": {
                    "type": "string",
                    "description": "List bonuses for this specific assignment only. Provide either this OR hit_id, not both."
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of bonus payments to return, between 1 and 100. Defaults to 100.",
                    "default": 100,
                    "minimum": 1,
                    "maximum": 100
                },
            },
            "required": [],
        },
        list_bonus_payments,
    )
