"""AWS MTurk client wrapper with environment-based configuration."""

import os
import sys
import boto3
from botocore.exceptions import ClientError, NoCredentialsError

_client = None

SANDBOX_ENDPOINT = "https://mturk-requester-sandbox.us-east-1.amazonaws.com"


def get_mturk_client():
    """Get or create the MTurk client singleton."""
    global _client
    if _client is None:
        use_sandbox = os.environ.get("MTURK_SANDBOX", "false").lower() == "true"
        endpoint_url = SANDBOX_ENDPOINT if use_sandbox else None

        _client = boto3.client(
            "mturk",
            region_name="us-east-1",
            endpoint_url=endpoint_url,
            aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"),
            aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"),
        )

        # Log which environment we're using
        env_name = "SANDBOX" if use_sandbox else "PRODUCTION"
        print(f"[mturk-mcp] Connected to MTurk {env_name}", file=sys.stderr)

    return _client


def is_sandbox() -> bool:
    """Check if we're using the sandbox environment."""
    return os.environ.get("MTURK_SANDBOX", "false").lower() == "true"


def wrap_html_question(html_content: str) -> str:
    """Wrap HTML content in MTurk's HTMLQuestion format."""
    return f"""<?xml version="1.0" encoding="UTF-8"?>
<HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd">
  <HTMLContent><![CDATA[
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <script type="text/javascript" src="https://s3.amazonaws.com/mturk-public/externalHIT_v1.js"></script>
</head>
<body>
  <form name="mturk_form" method="post" id="mturk_form" action="https://www.mturk.com/mturk/externalSubmit">
    <input type="hidden" name="assignmentId" id="assignmentId" value="">
    {html_content}
    <p><input type="submit" id="submitButton" value="Submit"></p>
  </form>
  <script>
    turkSetAssignmentID();
  </script>
</body>
</html>
]]></HTMLContent>
  <FrameHeight>600</FrameHeight>
</HTMLQuestion>"""


def format_error(e: Exception) -> str:
    """Format AWS errors into user-friendly messages."""
    if isinstance(e, NoCredentialsError):
        return "AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables."
    if isinstance(e, ClientError):
        error_code = e.response.get("Error", {}).get("Code", "Unknown")
        error_msg = e.response.get("Error", {}).get("Message", str(e))
        return f"MTurk API error ({error_code}): {error_msg}"
    return f"Error: {str(e)}"
