"""Data models for toil tracking and analysis."""
from dataclasses import dataclass, field
from enum import Enum


class Severity(str, Enum):
    CRITICAL = "critical"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"
    INFO = "info"


class ToilCategory(str, Enum):
    MANUAL_INTERVENTION = "manual_intervention"
    REPETITIVE_TASK = "repetitive_task"
    INCIDENT_RESPONSE = "incident_response"
    DEPLOYMENT = "deployment"
    SCALING = "scaling"
    MONITORING = "monitoring"
    ACCESS_MANAGEMENT = "access_management"
    DATA_MANAGEMENT = "data_management"
    CERTIFICATE_ROTATION = "certificate_rotation"
    CONFIGURATION = "configuration"


class AutomationPotential(str, Enum):
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"
    NONE = "none"


class TaskFrequency(str, Enum):
    HOURLY = "hourly"
    DAILY = "daily"
    WEEKLY = "weekly"
    MONTHLY = "monthly"
    QUARTERLY = "quarterly"
    AD_HOC = "ad_hoc"


FREQUENCY_ANNUAL_MULTIPLIER = {
    TaskFrequency.HOURLY: 8760,
    TaskFrequency.DAILY: 365,
    TaskFrequency.WEEKLY: 52,
    TaskFrequency.MONTHLY: 12,
    TaskFrequency.QUARTERLY: 4,
    TaskFrequency.AD_HOC: 12,
}


@dataclass
class ToilTask:
    name: str = ""
    description: str = ""
    category: ToilCategory = ToilCategory.MANUAL_INTERVENTION
    frequency: TaskFrequency = TaskFrequency.WEEKLY
    duration_minutes: float = 30.0
    team_size: int = 1
    is_automatable: bool = True
    automation_potential: AutomationPotential = AutomationPotential.MEDIUM
    automation_effort_hours: float = 40.0
    owner: str = ""
    service: str = ""
    labels: dict[str, str] = field(default_factory=dict)

    @property
    def annual_hours(self) -> float:
        multiplier = FREQUENCY_ANNUAL_MULTIPLIER.get(self.frequency, 12)
        return (self.duration_minutes / 60.0) * multiplier * self.team_size

    @property
    def automation_roi_months(self) -> float:
        if self.annual_hours == 0:
            return float("inf")
        monthly_savings = self.annual_hours / 12.0
        if monthly_savings == 0:
            return float("inf")
        return self.automation_effort_hours / monthly_savings


@dataclass
class Finding:
    rule_id: str = ""
    title: str = ""
    severity: Severity = Severity.INFO
    task_name: str = ""
    category: str = ""
    description: str = ""
    recommendation: str = ""


@dataclass
class ToilReport:
    tasks: list[ToilTask] = field(default_factory=list)
    findings: list[Finding] = field(default_factory=list)
    total_tasks: int = 0
    total_annual_hours: float = 0.0
    automatable_hours: float = 0.0
    automation_coverage: float = 0.0
    critical_count: int = 0
    high_count: int = 0
    medium_count: int = 0
    low_count: int = 0
    info_count: int = 0
    health_score: float = 100.0
    grade: str = "A"

    def compute_summary(self):
        self.total_tasks = len(self.tasks)
        self.total_annual_hours = sum(t.annual_hours for t in self.tasks)
        self.automatable_hours = sum(t.annual_hours for t in self.tasks if t.is_automatable)
        if self.total_annual_hours > 0:
            self.automation_coverage = (1.0 - self.automatable_hours / self.total_annual_hours) * 100
        else:
            self.automation_coverage = 100.0
        self.critical_count = sum(1 for f in self.findings if f.severity == Severity.CRITICAL)
        self.high_count = sum(1 for f in self.findings if f.severity == Severity.HIGH)
        self.medium_count = sum(1 for f in self.findings if f.severity == Severity.MEDIUM)
        self.low_count = sum(1 for f in self.findings if f.severity == Severity.LOW)
        self.info_count = sum(1 for f in self.findings if f.severity == Severity.INFO)
        penalty = (self.critical_count * 15) + (self.high_count * 10) + (self.medium_count * 5) + (self.low_count * 2)
        self.health_score = max(0.0, 100.0 - penalty)
        if self.health_score >= 90:
            self.grade = "A"
        elif self.health_score >= 80:
            self.grade = "B"
        elif self.health_score >= 70:
            self.grade = "C"
        elif self.health_score >= 60:
            self.grade = "D"
        else:
            self.grade = "F"


TOIL_RULES = {
    "TOIL-001": {
        "title": "High-Frequency Manual Task",
        "severity": Severity.CRITICAL,
        "description": "Task runs daily or more frequently and is performed manually",
        "recommendation": "Prioritize automation — high-frequency manual work is the biggest source of toil",
    },
    "TOIL-002": {
        "title": "High Annual Time Investment",
        "severity": Severity.HIGH,
        "description": "Task consumes more than 200 hours per year",
        "recommendation": "Evaluate automation or process improvement to reduce time investment",
    },
    "TOIL-003": {
        "title": "Quick Automation ROI",
        "severity": Severity.HIGH,
        "description": "Automation would pay for itself within 3 months",
        "recommendation": "Automate immediately — rapid return on investment",
    },
    "TOIL-004": {
        "title": "Multi-Person Toil",
        "severity": Severity.MEDIUM,
        "description": "Task requires multiple team members, multiplying toil impact",
        "recommendation": "Automate or create self-service tooling to reduce team coordination",
    },
    "TOIL-005": {
        "title": "Incident-Related Toil",
        "severity": Severity.HIGH,
        "description": "Manual incident response task that could be automated",
        "recommendation": "Build runbooks and automation to reduce MTTR",
    },
    "TOIL-006": {
        "title": "Deployment Toil",
        "severity": Severity.MEDIUM,
        "description": "Manual deployment steps that should be in CI/CD pipeline",
        "recommendation": "Integrate into CI/CD pipeline for automated deployments",
    },
    "TOIL-007": {
        "title": "Access Management Toil",
        "severity": Severity.MEDIUM,
        "description": "Manual access provisioning/deprovisioning",
        "recommendation": "Implement RBAC with self-service portal or SCIM provisioning",
    },
    "TOIL-008": {
        "title": "Scaling Toil",
        "severity": Severity.HIGH,
        "description": "Manual scaling operations that should be autoscaled",
        "recommendation": "Configure HPA/VPA or cloud autoscaling policies",
    },
    "TOIL-009": {
        "title": "Low Automation Potential Task",
        "severity": Severity.LOW,
        "description": "Task has low automation potential but still consumes time",
        "recommendation": "Consider process improvement or documentation to reduce duration",
    },
    "TOIL-010": {
        "title": "Toil Budget Exceeded",
        "severity": Severity.CRITICAL,
        "description": "Total toil exceeds the recommended 50% engineering time threshold",
        "recommendation": "Declare a toil reduction sprint — automation debt is critical",
    },
}
