from sqlalchemy.orm import Session

from .. import models


GENERAL_RECOMMENDATIONS = {
    "Critical": [
        "Darhol firewall, IPS va monitoring qoidalarini kuchaytirish.",
        "Tarmoq segmentatsiyasini joriy etish va muhim aktivlarni ajratish.",
        "Backup siyosatini tekshirish, 2FA va log auditni majburiy qilish.",
    ],
    "High": [
        "Zaifliklarni ustuvor tartibda bartaraf etish va SIEM kuzatuvini kuchaytirish.",
        "Muhim servislar uchun kirish nazorati va shifrlashni kuchaytirish.",
    ],
    "Medium": [
        "Parol siyosatini kuchaytirish va konfiguratsiyalarni tekshirish.",
        "Email security, monitoring va foydalanuvchi treninglarini yangilash.",
    ],
    "Low": [
        "Doimiy monitoring va muntazam auditni davom ettirish.",
        "Himoya texnologiyalari samaradorligini davriy qayta baholash.",
    ],
}


def build_recommendations(db: Session, threat_id: int, risk_level: str) -> list[str]:
    stored = (
        db.query(models.Recommendation)
        .filter(models.Recommendation.threat_id == threat_id)
        .order_by(models.Recommendation.priority.desc(), models.Recommendation.id.asc())
        .all()
    )

    recommendations = [item.recommendation_text for item in stored]
    recommendations.extend(GENERAL_RECOMMENDATIONS.get(risk_level, []))
    return list(dict.fromkeys(recommendations))
