from datetime import UTC, datetime, timedelta

from home_agent.contracts.types import Item, ItemKind, UrgencyDecision, UrgencyLabel

IMPORTANT_KEYWORDS = {"urgent", "asap", "deadline", "exam", "assignment", "university"}
IMPORTANT_SENDERS = {"noreply@university.edu", "professor@university.edu"}


class RuleUrgencyEngine:
    def score(self, item: Item) -> UrgencyDecision:
        reasons: list[str] = []
        score = 0.0

        subject = item.subject.lower()
        if any(keyword in subject for keyword in IMPORTANT_KEYWORDS):
            score += 0.45
            reasons.append("keyword-match")

        if item.sender.lower() in IMPORTANT_SENDERS:
            score += 0.4
            reasons.append("trusted-sender")

        if item.kind == ItemKind.CALENDAR_EVENT:
            event_start = item.metadata.get("start_at")
            if isinstance(event_start, str):
                parsed = datetime.fromisoformat(event_start)
                if parsed.tzinfo is None:
                    parsed = parsed.replace(tzinfo=UTC)
                if parsed - datetime.now(tz=UTC) <= timedelta(hours=24):
                    score += 0.5
                    reasons.append("time-proximity")

        if score >= 0.9:
            label = UrgencyLabel.CRITICAL
        elif score >= 0.7:
            label = UrgencyLabel.HIGH
        elif score >= 0.4:
            label = UrgencyLabel.MEDIUM
        else:
            label = UrgencyLabel.LOW

        return UrgencyDecision(score=score, label=label, reasons=reasons, used_llm=False)
