"""Renewals due soon with no activity 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
from ..utils import days_since


class RenewalsDueNoActivityCheck(BaseRenewalCheck):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._has_next_step = True
        self._has_activity = True

    def build_count_filters(self) -> Tuple[str, List[FilterExpr]]:
        cfg = self._resolve_renewal_config()
        horizon_days = int(self.params.get("horizon_days", 90))
        start, end = self._today_values(horizon_days)
        filters: List[FilterExpr] = [
            Filter(cfg.renewal_date_field, FilterOp.GTE, start),
            Filter(cfg.renewal_date_field, FilterOp.LTE, end),
        ]
        if self.provider.name == "salesforce" and cfg.object_type == "contract":
            filters.append(Filter("Status", FilterOp.NEQ, "Expired"))
        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()
        horizon_days = int(self.params.get("horizon_days", 90))
        start, end = self._today_values(horizon_days)
        filters: List[FilterExpr] = [
            Filter(cfg.renewal_date_field, FilterOp.GTE, start),
            Filter(cfg.renewal_date_field, FilterOp.LTE, end),
        ]
        if self.provider.name == "salesforce" and cfg.object_type == "contract":
            filters.append(Filter("Status", FilterOp.NEQ, "Expired"))

        fields = [
            "Id",
            cfg.renewal_date_field,
            cfg.account_id_field,
            cfg.account_name_field,
            "OwnerId",
            "Status",
            "LastActivityDate",
            "LastModifiedDate",
            "NextStep",
        ]
        fields = self._filter_fields(cfg.object_type, list(dict.fromkeys(fields)))
        self._has_next_step = "NextStep" in fields
        self._has_activity = "LastActivityDate" in fields or "LastModifiedDate" in 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()
        horizon_days = int(self.params.get("horizon_days", 90))
        inactive_days = int(self.params.get("inactive_days", 14))

        for row in rows:
            record_id = row.get("Id", "")
            if not record_id:
                continue
            renewal_date = row.get(cfg.renewal_date_field)
            days_until = self._days_until(str(renewal_date) if renewal_date is not None else None)
            if days_until is None or days_until > horizon_days:
                continue

            activity_value = row.get("LastActivityDate") or row.get("LastModifiedDate")
            days_since_activity = None
            if self._has_activity:
                days_since_activity = days_since(str(activity_value) if activity_value is not None else None)
            next_step = row.get("NextStep")

            base_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"),
                "LastActivityDate": row.get("LastActivityDate"),
                "LastModifiedDate": row.get("LastModifiedDate"),
                "days_until_renewal": days_until,
                "days_since_activity": days_since_activity,
            }

            if self._has_activity and (days_since_activity is None or days_since_activity >= inactive_days):
                evidence.append(
                    EvidenceRow(
                        record_id=record_id,
                        sobject=cfg.object_type,
                        fields=dict(base_fields),
                        reason=f"No activity in {days_since_activity or 'unknown'} days on upcoming renewal",
                        reason_code="NO_ACTIVITY",
                        severity=self.definition.severity_default,
                    )
                )

            if self._has_next_step and (next_step is None or str(next_step).strip() == ""):
                evidence.append(
                    EvidenceRow(
                        record_id=record_id,
                        sobject=cfg.object_type,
                        fields=dict(base_fields),
                        reason=f"Renewal due in {days_until} days with no next step",
                        reason_code="MISSING_NEXT_STEP",
                        severity=self.definition.severity_default,
                    )
                )

        return evidence

    def get_recommended_actions(self) -> List[RecommendedAction]:
        return [
            RecommendedAction(
                action_type="create_task",
                label="Create renewal follow-up tasks",
                risk_level="low",
            ),
            RecommendedAction(
                action_type="export_csv",
                label="Export renewals with no activity to CSV",
                risk_level="safe",
            ),
        ]


__all__ = ["RenewalsDueNoActivityCheck"]
