import re
import logging

logger = logging.getLogger("soagila.airlock.classifier")

# Classification keywords
CLASSIFICATION_KEYWORDS = {
    "financial": {
        "bank", "credit", "debit", "loan", "mortgage", "interest", "rate",
        "fee", "payment", "transfer", "balance", "account", "deposit",
        "withdrawal", "investment", "portfolio", "stock", "bond", "fund",
        "kredi", "faiz", "hesap", "ödeme", "havale", "eft", "bakiye",
        "yatırım", "borsa", "kart", "aidat", "masraf", "döviz", "kur",
        "currency", "forex", "trade", "dividend", "iban", "swift",
    },
    "personal": {
        "name", "address", "phone", "email", "birthday", "age", "family",
        "isim", "adres", "telefon", "doğum", "yaş", "aile",
        "preference", "hobby", "occupation", "job", "meslek",
    },
    "medical": {
        "health", "medical", "diagnosis", "prescription", "doctor",
        "hospital", "patient", "treatment", "surgery", "symptom",
        "sağlık", "hastane", "doktor", "tedavi", "ilaç", "reçete",
        "blood", "test", "lab", "insurance", "sigorta",
    },
}


def classify_content(text: str) -> str:
    """
    Classify content into: financial, personal, medical, or general.
    Uses keyword frequency analysis.
    """
    text_lower = text.lower()
    words = set(re.findall(r'\b\w{3,}\b', text_lower))

    scores = {}
    for category, keywords in CLASSIFICATION_KEYWORDS.items():
        overlap = words & keywords
        scores[category] = len(overlap)

    if not scores or max(scores.values()) == 0:
        return "general"

    best_category = max(scores, key=scores.get)
    if scores[best_category] >= 1:
        return best_category

    return "general"


def assess_importance(text: str, classification: str, pii_found: bool) -> float:
    """
    Assess importance of content (0.0 to 1.0).
    Higher importance = longer TTL in working memory, higher initial relevance.
    """
    importance = 0.5  # base

    # PII presence increases importance
    if pii_found:
        importance += 0.2

    # Classification-based adjustment
    classification_weights = {
        "financial": 0.15,
        "medical": 0.2,
        "personal": 0.1,
        "general": 0.0,
    }
    importance += classification_weights.get(classification, 0.0)

    # Length-based (longer messages tend to be more informative)
    word_count = len(text.split())
    if word_count > 20:
        importance += 0.1

    return min(importance, 1.0)
