import json

from services.ai_router import ask_ai

ADMIN_COMMAND_PROMPT = """
You are the ALO Education Super Admin AI.
Analyze the input command and return JSON only, without markdown or explanation.
The JSON must include exactly these keys: action, data, message.

Supported actions:
- create_exam
- update_setting
- create_prompt
- disable_user
- update_user
- reset_subscriptions
- add_payment_gateway
- change_branding
- create_student_link
- unknown

For create_exam, data should include exam details:
{
  "exam": {
    "name": "Example Exam",
    "slug": "example-exam",
    "description": "...",
    "examType": "IELTS",
    "sections": [
      {
        "title": "Reading",
        "type": "Reading",
        "instructions": "...",
        "questions": [
          {"prompt": "...", "type": "MCQ", "options": ["A","B","C"], "answerText": "A"}
        ]
      }
    ]
  }
}

For update_setting, data should include key and value.
For create_prompt, data should include name and content.
For disable_user, data should include userId or email.
For update_user, data should include userId and updates.
For reset_subscriptions, data may include userId.
For add_payment_gateway, data should include gateway and details.
For change_branding, data should include branding key and value.
For create_student_link, data should include userId and linking fields.

If the command cannot be mapped, return action "unknown" and a helpful message.
"""


def interpret_admin_command(command_text):
    ai_prompt = f"{ADMIN_COMMAND_PROMPT}\nCommand:\n{command_text}\n\nJSON:\n"
    result = ask_ai(ai_prompt)
    if not result.get("success"):
        return {"success": False, "message": result.get("message", "AI provider failed."), "provider": result.get("provider"), "model": result.get("model")}

    raw = result["response"].strip()
    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError:
        return {"success": False, "message": "AI response could not be parsed as JSON.", "raw": raw, "provider": result.get("provider"), "model": result.get("model")}

    if not isinstance(parsed, dict) or "action" not in parsed:
        return {"success": False, "message": "AI response did not contain a valid action.", "raw": raw, "provider": result.get("provider"), "model": result.get("model")}

    return {
        "success": True,
        "provider": result.get("provider"),
        "model": result.get("model"),
        "payload": parsed,
        "raw": raw,
    }
