"""Qualification management tools for controlling worker access."""

import json
from mcp.types import TextContent

from ..client import get_mturk_client, format_error


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

    async def create_qualification_type(args: dict) -> list[TextContent]:
        """Create a new qualification type that can be assigned to workers."""
        try:
            client = get_mturk_client()
            params = {
                "Name": args["name"],
                "Description": args["description"],
                "QualificationTypeStatus": "Active",
            }
            if args.get("keywords"):
                params["Keywords"] = args["keywords"]
            if args.get("auto_granted"):
                params["AutoGranted"] = True
                if args.get("auto_granted_value") is not None:
                    params["AutoGrantedValue"] = args["auto_granted_value"]

            response = client.create_qualification_type(**params)
            qt = response["QualificationType"]
            result = {
                "qualification_type_id": qt["QualificationTypeId"],
                "name": qt["Name"],
                "description": qt["Description"],
                "status": qt["QualificationTypeStatus"],
                "auto_granted": qt.get("AutoGranted", False),
                "creation_time": str(qt["CreationTime"]),
            }
            return [TextContent(type="text", text=json.dumps(result, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "create_qualification_type",
        """Creates a new custom qualification that you can assign to workers to control who can work on your HITs.

Use this tool to create filters for your workforce. Common use cases:
- Create a "Trusted Worker" qualification to give to workers who do good work
- Create a "Completed My Training" qualification after workers pass a test HIT
- Create a "Banned" qualification to exclude specific workers from future HITs

Qualifications have integer values (default 1), allowing tiered systems. For example, a "Skill Level" qualification could have values 1-5, and you could require workers to have level 3+ for advanced HITs.

After creating a qualification, you can:
1. Assign it to specific workers with assign_qualification
2. Require it for HITs (add QualificationRequirements when creating HITs - not yet supported in this tool)

If auto_granted is true, workers automatically receive this qualification when they request it - useful for opt-in lists. If false (default), you manually assign it to workers.

Returns the qualification_type_id which you'll need for assigning it to workers.""",
        {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Name of the qualification, shown to workers if they can request it. Make it descriptive. Examples: 'Trusted Survey Responder', 'Completed Training HIT', 'English Native Speaker'"
                },
                "description": {
                    "type": "string",
                    "description": "Detailed description explaining what this qualification means and how workers can obtain it. Workers see this when browsing qualifications."
                },
                "keywords": {
                    "type": "string",
                    "description": "Optional comma-separated keywords to help workers find this qualification if it's requestable. Example: 'survey, trusted, experienced'"
                },
                "auto_granted": {
                    "type": "boolean",
                    "description": "If true, workers who request this qualification automatically receive it. Use for opt-in lists. If false (default), you must manually assign it with assign_qualification.",
                    "default": False
                },
                "auto_granted_value": {
                    "type": "integer",
                    "description": "The integer value to auto-grant. Only used if auto_granted is true. Default is 1. Use higher values for tiered qualification systems."
                },
            },
            "required": ["name", "description"],
        },
        create_qualification_type,
    )

    async def list_qualification_types(args: dict) -> list[TextContent]:
        """List available qualification types."""
        try:
            client = get_mturk_client()
            params = {
                "MustBeRequestable": args.get("must_be_requestable", True),
                "MaxResults": min(args.get("max_results", 100), 100),
            }
            if args.get("must_be_owned_by_caller") is not None:
                params["MustBeOwnedByCaller"] = args["must_be_owned_by_caller"]
            if args.get("query"):
                params["Query"] = args["query"]

            response = client.list_qualification_types(**params)
            types = response.get("QualificationTypes", [])
            result = {
                "count": len(types),
                "qualification_types": [
                    {
                        "qualification_type_id": qt["QualificationTypeId"],
                        "name": qt["Name"],
                        "description": qt.get("Description"),
                        "status": qt["QualificationTypeStatus"],
                        "auto_granted": qt.get("AutoGranted", False),
                    }
                    for qt in types
                ],
            }
            return [TextContent(type="text", text=json.dumps(result, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "list_qualification_types",
        """Lists qualification types available on MTurk, including your custom qualifications and system qualifications.

Use this tool to:
- Find qualification_type_ids for qualifications you've created (set must_be_owned_by_caller=true)
- Browse available system qualifications (like Worker_NumberHITsApproved, Worker_Locale, etc.)
- Search for specific qualifications by name

System qualifications (owned by MTurk) include useful built-in filters:
- Worker_NumberHITsApproved: Total HITs the worker has completed
- Worker_PercentAssignmentsApproved: Worker's approval rate
- Worker_Locale: Worker's country (useful for language/region targeting)
- Worker_Adult: Workers who agreed to do adult content

To use your custom qualifications:
1. Create them with create_qualification_type
2. Find their IDs with this tool (must_be_owned_by_caller=true)
3. Assign to workers with assign_qualification

Note: This tool lists qualification TYPES, not which workers have them. To check a specific worker's qualifications, use get_qualification_score.""",
        {
            "type": "object",
            "properties": {
                "must_be_requestable": {
                    "type": "boolean",
                    "description": "If true (default), only show qualifications that workers can request. Set to false to include non-requestable qualifications.",
                    "default": True
                },
                "must_be_owned_by_caller": {
                    "type": "boolean",
                    "description": "If true, only show qualifications YOU created. Useful for finding your custom qualification IDs. If false or omitted, shows all qualifications including system ones."
                },
                "query": {
                    "type": "string",
                    "description": "Search query to filter qualifications by name. Example: 'trusted' to find qualifications with 'trusted' in the name."
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of qualifications to return, between 1 and 100. Defaults to 100.",
                    "default": 100,
                    "minimum": 1,
                    "maximum": 100
                },
            },
            "required": [],
        },
        list_qualification_types,
    )

    async def assign_qualification(args: dict) -> list[TextContent]:
        """Assign a qualification to a worker."""
        try:
            client = get_mturk_client()
            client.associate_qualification_with_worker(
                QualificationTypeId=args["qualification_type_id"],
                WorkerId=args["worker_id"],
                IntegerValue=args.get("value", 1),
                SendNotification=args.get("send_notification", True),
            )
            return [TextContent(type="text", text=json.dumps({
                "success": True,
                "qualification_type_id": args["qualification_type_id"],
                "worker_id": args["worker_id"],
                "value": args.get("value", 1),
            }, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "assign_qualification",
        """Grants a qualification to a specific worker, allowing or preventing them from working on HITs that require that qualification.

Use this tool to:
- Reward good workers: Give trusted workers a qualification that grants access to premium HITs
- Build worker pools: Create a "Completed Onboarding" qualification and assign it after workers pass a test
- Create exclusion lists: Assign a "Do Not Use" qualification and require workers NOT have it (value=0) for your HITs

The value parameter allows tiered systems. For example:
- Skill Level 1, 2, 3... for different task difficulties
- 1 = has qualification, 0 = blocked (when your HIT requires value > 0)

By default, workers are notified when they receive a qualification. Set send_notification=false for silent assignments (useful for internal tracking or blocklists).

You can update a worker's qualification value by calling this again with a different value - it overwrites the previous value.

To remove a qualification entirely, use revoke_qualification instead.""",
        {
            "type": "object",
            "properties": {
                "qualification_type_id": {
                    "type": "string",
                    "description": "The qualification type ID to assign. Get this from create_qualification_type or list_qualification_types (with must_be_owned_by_caller=true for your custom qualifications)."
                },
                "worker_id": {
                    "type": "string",
                    "description": "The worker ID to assign the qualification to. Get worker IDs from list_assignments - each submission includes the worker_id."
                },
                "value": {
                    "type": "integer",
                    "description": "Integer value for the qualification. Default is 1. Use different values for tiered systems (e.g., skill levels 1-5) or use 0 to effectively block a worker from HITs requiring value > 0.",
                    "default": 1
                },
                "send_notification": {
                    "type": "boolean",
                    "description": "Whether to notify the worker they received this qualification. Default is true. Set to false for internal tracking or blocklists where you don't want workers to know.",
                    "default": True
                },
            },
            "required": ["qualification_type_id", "worker_id"],
        },
        assign_qualification,
    )

    async def revoke_qualification(args: dict) -> list[TextContent]:
        """Revoke a qualification from a worker."""
        try:
            client = get_mturk_client()
            params = {
                "QualificationTypeId": args["qualification_type_id"],
                "WorkerId": args["worker_id"],
            }
            if args.get("reason"):
                params["Reason"] = args["reason"]

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

    register(
        "revoke_qualification",
        """Removes a qualification from a worker, potentially blocking them from HITs that require it.

Use this tool to:
- Remove trusted status from a worker who started submitting poor work
- Clean up after a worker completes a limited-time project
- Undo an accidental qualification assignment

The worker loses access to any HITs requiring this qualification. If you just want to change their qualification value (e.g., demote from level 3 to level 1), use assign_qualification instead - it overwrites the existing value.

You can provide an optional reason, but the worker may or may not see it depending on MTurk's notification settings.

Note: This only affects YOUR qualification. You cannot revoke system qualifications or qualifications created by other requesters.""",
        {
            "type": "object",
            "properties": {
                "qualification_type_id": {
                    "type": "string",
                    "description": "The qualification type ID to revoke. Must be a qualification you created."
                },
                "worker_id": {
                    "type": "string",
                    "description": "The worker ID to remove the qualification from."
                },
                "reason": {
                    "type": "string",
                    "description": "Optional explanation for why the qualification is being revoked. Example: 'Quality of work declined' or 'Project completed'"
                },
            },
            "required": ["qualification_type_id", "worker_id"],
        },
        revoke_qualification,
    )

    async def get_qualification_score(args: dict) -> list[TextContent]:
        """Get a worker's score for a specific qualification."""
        try:
            client = get_mturk_client()
            response = client.get_qualification_score(
                QualificationTypeId=args["qualification_type_id"],
                WorkerId=args["worker_id"],
            )
            q = response.get("Qualification", {})
            result = {
                "qualification_type_id": q.get("QualificationTypeId"),
                "worker_id": q.get("WorkerId"),
                "value": q.get("IntegerValue"),
                "status": q.get("Status"),
                "grant_time": str(q.get("GrantTime")) if q.get("GrantTime") else None,
            }
            return [TextContent(type="text", text=json.dumps(result, indent=2))]
        except Exception as e:
            return [TextContent(type="text", text=format_error(e))]

    register(
        "get_qualification_score",
        """Checks whether a specific worker has a specific qualification, and what value they have.

Use this tool to:
- Verify a worker has completed your training before assigning premium tasks
- Check a worker's qualification level in a tiered system
- Confirm a qualification was successfully assigned

Returns the qualification value (integer) and when it was granted. If the worker doesn't have the qualification, you'll get an error indicating that.

For system qualifications (like Worker_NumberHITsApproved), this returns MTurk's current value for that worker. For your custom qualifications, it returns the value you assigned.

Note: This checks one worker for one qualification. To see all qualifications a worker has, or all workers with a qualification, you'd need multiple calls or different approaches.""",
        {
            "type": "object",
            "properties": {
                "qualification_type_id": {
                    "type": "string",
                    "description": "The qualification type ID to check. Can be your custom qualification or a system qualification like Worker_NumberHITsApproved."
                },
                "worker_id": {
                    "type": "string",
                    "description": "The worker ID to check. Get worker IDs from list_assignments."
                },
            },
            "required": ["qualification_type_id", "worker_id"],
        },
        get_qualification_score,
    )
