"""Renewals overdue check."""

from __future__ import annotations

from typing import Any, Dict, List, Tuple

from .renewals_base import BaseRenewalCheck
from ..crm_provider import Filter, FilterExpr, FilterOp
from ..models import EvidenceRow, RecommendedAction


class RenewalsOverdueCheck(BaseRenewalCheck):
    def _overdue_bounds(self, max_overdue_days: int) -> tuple[Any, Any]:
        start, _ = self._today_values(None)
        if self.provider.name == "hubspot":
            overdue_start = int(start - max_overdue_days * 86400000)
        else:
            from datetime import datetime, timedelta, timezone

            today = datetime.now(timezone.utc).date()
            overdue_start = (today - timedelta(days=max_overdue_days)).isoformat()
        return start, overdue_start

    def build_count_filters(self) -> Tuple[str, List[FilterExpr]]:
        cfg = self._resolve_renewal_config()
        max_overdue_days = int(self.params.get("max_overdue_days", 180))
        start, overdue_start = self._overdue_bounds(max_overdue_days)

        filters: List[FilterExpr] = [
            Filter(cfg.renewal_date_field, FilterOp.LT, start),
            Filter(cfg.renewal_date_field, FilterOp.GTE, overdue_start),
        ]
        if self.provider.name == "salesforce" and cfg.object_type == "contract":
            filters.append(Filter("Status", FilterOp.EQ, "Activated"))
        return cfg.object_type, filters

    def build_sample_request(self) -> Tuple[str, List[str], List[FilterExpr], str | None, str, bool]:
        cfg = self._resolve_renewal_config()
        max_overdue_days = int(self.params.get("max_overdue_days", 180))
        start, overdue_start = self._overdue_bounds(max_overdue_days)

        filters: List[FilterExpr] = [
            Filter(cfg.renewal_date_field, FilterOp.LT, start),
            Filter(cfg.renewal_date_field, FilterOp.GTE, overdue_start),
        ]
        if self.provider.name == "salesforce" and cfg.object_type == "contract":
            filters.append(Filter("Status", FilterOp.EQ, "Activated"))

        fields = [
            "Id",
            cfg.renewal_date_field,
            cfg.account_id_field,
            cfg.account_name_field,
            "OwnerId",
            "Status",
        ]
        fields = self._filter_fields(cfg.object_type, list(dict.fromkeys(fields)))
        return cfg.object_type, fields, filters, cfg.renewal_date_field, "ASC", False

    def evaluate(self, rows: List[Dict[str, Any]]) -> List[EvidenceRow]:
        evidence: List[EvidenceRow] = []
        cfg = self._resolve_renewal_config()
        for row in rows:
            record_id = row.get("Id", "")
            if not record_id:
                continue
            renewal_date = row.get(cfg.renewal_date_field)
            days_overdue = self._days_overdue(str(renewal_date) if renewal_date is not None else None)
            if days_overdue is None:
                continue
            fields = {
                "AccountName": row.get(cfg.account_name_field),
                "AccountId": row.get(cfg.account_id_field),
                "RenewalDate": renewal_date,
                "OwnerId": row.get("OwnerId"),
                "Status": row.get("Status"),
                "days_overdue": days_overdue,
            }
            evidence.append(
                EvidenceRow(
                    record_id=record_id,
                    sobject=cfg.object_type,
                    fields=fields,
                    reason=f"Renewal overdue by {days_overdue} days",
                    reason_code="RENEWAL_OVERDUE",
                    severity=self.definition.severity_default,
                )
            )
        return evidence

    def get_recommended_actions(self) -> List[RecommendedAction]:
        return [
            RecommendedAction(
                action_type="create_task",
                label="Create tasks for overdue renewals",
                risk_level="low",
            ),
            RecommendedAction(
                action_type="flag_record",
                label="Flag overdue renewals",
                risk_level="low",
            ),
            RecommendedAction(
                action_type="export_csv",
                label="Export overdue renewals to CSV",
                risk_level="safe",
            ),
        ]


__all__ = ["RenewalsOverdueCheck"]
