import ast
from .models import call_model_text

RED_TEAM_MODEL = "gpt-4o-mini"

RED_TEAM_SYSTEM_PROMPT = """
You are the RED TEAM security agent.
Your job is to analyze the user's prompt and identify ALL potential security issues.

ALWAYS output a Python list with at least 5 findings.
NO explanations. NO markdown. ONLY a list.
Example:
[
  "[coverage_gap] Missing HTTPS",
  "[auth_risk] No password hashing",
  "[injection_risk] Missing input sanitization",
  "[misconfiguration] Missing rate limiting",
  "[sensitive_data] Risk of logging credentials"
]
"""

def _parse_findings(raw: str):
    try:
        findings = ast.literal_eval(raw)
        if not isinstance(findings, list) or len(findings) < 1:
            raise ValueError
        return [str(x) for x in findings]
    except:
        return [
            "[parse_error] Model returned non-structured output.",
            f"[raw_output] {raw[:200]}..."
        ]

def run_red_team(original_prompt: str):
    raw = call_model_text(
        model_name=RED_TEAM_MODEL,
        system_prompt=RED_TEAM_SYSTEM_PROMPT,
        user_prompt=original_prompt,
        temperature=0.1,
    )
    return _parse_findings(raw)
