from typing import Any

from .base import Middleware


class ModerationMiddleware(Middleware):
    @property
    def name(self) -> str:
        return "moderation"

    @property
    def description(self) -> str:
        return "Checks user input for dangerous or inappropriate content"

    def _default_instructions(self) -> str:
        return """You are a content moderation assistant. Your task is to analyze user input and determine if it contains clearly dangerous, harmful, or inappropriate content.

You must respond with a JSON object in the following format:
```json
{
  "is_safe": true or false,
  "reason": "explanation if unsafe, otherwise empty string"
}
```

Only flag content as unsafe if it clearly falls into these categories:
1. Violence - requests for violent actions, self-harm, harm to others
2. Illegal activities - requests for help with crimes
3. Security threats - requests for hacking, malware creation
4. Explicit harmful content - hate speech, extreme discrimination
5. Sexually explicit content - pornographic material
6. Real personal info - requests to generate personal info about real people

Be lenient with:
- General programming questions
- File operations (read, write, find)
- System information requests
- Educational or informational queries
- Normal conversations
- Most user commands and requests

If you're unsure whether content is dangerous, err on the side of allowing it (set "is_safe" to true)."""

    async def execute(self, context: Any) -> tuple[bool, str]:
        import json

        json_input = context.to_json_input(self.name)
        output = await self._run_agent(json_input)

        context.add_result(self.name, json_input, output)

        try:
            start = output.find('{')
            end = output.rfind('}') + 1
            if start >= 0 and end > start:
                result = json.loads(output[start:end])
                if not result.get('is_safe', True):
                    reason = result.get('reason', 'Content rejected by moderation')
                    context.set_early_return(reason)
                    return False, json.dumps({
                        "is_safe": False,
                        "reason": reason
                    }, ensure_ascii=False)
        except Exception:
            pass

        return True, context.user_input


def get_moderation_middleware() -> ModerationMiddleware:
    return ModerationMiddleware()
