from openai import OpenAI
from django.conf import settings
from .models import Risk

def extract_risk_factors(organization):
    excluded_fields={"name","email"}
    risk_data = {}

    for field in organization._meta.get_fields():
        if field.name not in excluded_fields and hasattr(organization, field.name):
            value = getattr(organization, field.name)
            if value:
                risk_data[field.name] = value
    return risk_data

def get_top_risk(organization):
    client = OpenAI(api_key=settings.OPENAI_API_KEY)

    all_risks = Risk.objects.all()

    risk_list = []
    for risk in all_risks:
        risk_list.append(f"""
        Risk ID: {risk.risk_id}
        Category: {risk.category}
        Name: {risk.risk_name}
        Primary Impact: {risk.primary_impact}
        """)

    risk_factors = extract_risk_factors(organization)

    prompt = f"""
    You are an AI risk assessor. Based on the following company details and list of known risks,
    identify the 10 most critical risks for this company. Respond only with risk IDs.

    Company Details:
    {risk_factors}

    List of Risks:
    {risk_list}

    Provide only the 10 most critical risk IDs in a simple comma-separated format, e.g "1,3,7,12,..."
    """

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "system", "content": prompt}]
    )

    risk_ids = response.choices[0].message.content.strip().split(",")

    return [int(risk_id) for risk_id in risk_ids if risk_id.isdigit()]
