"""Toil analyzer — applies TOIL-001 to TOIL-010 rules."""
from ..models import (
    ToilTask, ToilReport, Finding, Severity, ToilCategory,
    TaskFrequency, AutomationPotential, TOIL_RULES,
)


def analyze_toil(tasks: list[ToilTask], team_capacity_hours: float = 2080.0) -> ToilReport:
    """Analyze toil tasks and produce a report."""
    report = ToilReport(tasks=tasks)
    for task in tasks:
        _check_high_frequency_manual(task, report)
        _check_high_annual_hours(task, report)
        _check_quick_roi(task, report)
        _check_multi_person(task, report)
        _check_incident_toil(task, report)
        _check_deployment_toil(task, report)
        _check_access_toil(task, report)
        _check_scaling_toil(task, report)
        _check_low_automation(task, report)
    # Check total toil budget after individual checks
    total_hours = sum(t.annual_hours for t in tasks)
    if total_hours > team_capacity_hours * 0.5:
        rule = TOIL_RULES["TOIL-010"]
        report.findings.append(Finding(
            rule_id="TOIL-010",
            title=rule["title"],
            severity=rule["severity"],
            task_name="(all tasks)",
            category="aggregate",
            description=f"Total toil is {total_hours:.0f}h/year ({total_hours/team_capacity_hours*100:.0f}% of capacity)",
            recommendation=rule["recommendation"],
        ))
    report.compute_summary()
    return report


def _make_finding(rule_id: str, task: ToilTask, **overrides) -> Finding:
    rule = TOIL_RULES[rule_id]
    return Finding(
        rule_id=rule_id,
        title=overrides.get("title", rule["title"]),
        severity=overrides.get("severity", rule["severity"]),
        task_name=task.name,
        category=task.category.value,
        description=overrides.get("description", rule["description"]),
        recommendation=overrides.get("recommendation", rule["recommendation"]),
    )


def _check_high_frequency_manual(task: ToilTask, report: ToilReport):
    """TOIL-001: High-frequency manual task."""
    if task.frequency in (TaskFrequency.HOURLY, TaskFrequency.DAILY) and task.is_automatable:
        report.findings.append(_make_finding("TOIL-001", task,
            description=f"'{task.name}' runs {task.frequency.value} and takes {task.duration_minutes}min each time"))


def _check_high_annual_hours(task: ToilTask, report: ToilReport):
    """TOIL-002: High annual time investment."""
    if task.annual_hours > 200:
        report.findings.append(_make_finding("TOIL-002", task,
            description=f"'{task.name}' consumes {task.annual_hours:.0f}h/year"))


def _check_quick_roi(task: ToilTask, report: ToilReport):
    """TOIL-003: Quick automation ROI."""
    if task.is_automatable and task.automation_roi_months <= 3:
        report.findings.append(_make_finding("TOIL-003", task,
            description=f"Automating '{task.name}' pays for itself in {task.automation_roi_months:.1f} months"))


def _check_multi_person(task: ToilTask, report: ToilReport):
    """TOIL-004: Multi-person toil."""
    if task.team_size > 1 and task.is_automatable:
        report.findings.append(_make_finding("TOIL-004", task,
            description=f"'{task.name}' requires {task.team_size} people per occurrence"))


def _check_incident_toil(task: ToilTask, report: ToilReport):
    """TOIL-005: Incident-related toil."""
    if task.category == ToilCategory.INCIDENT_RESPONSE and task.is_automatable:
        report.findings.append(_make_finding("TOIL-005", task))


def _check_deployment_toil(task: ToilTask, report: ToilReport):
    """TOIL-006: Deployment toil."""
    if task.category == ToilCategory.DEPLOYMENT and task.is_automatable:
        report.findings.append(_make_finding("TOIL-006", task))


def _check_access_toil(task: ToilTask, report: ToilReport):
    """TOIL-007: Access management toil."""
    if task.category == ToilCategory.ACCESS_MANAGEMENT and task.is_automatable:
        report.findings.append(_make_finding("TOIL-007", task))


def _check_scaling_toil(task: ToilTask, report: ToilReport):
    """TOIL-008: Scaling toil."""
    if task.category == ToilCategory.SCALING and task.is_automatable:
        report.findings.append(_make_finding("TOIL-008", task))


def _check_low_automation(task: ToilTask, report: ToilReport):
    """TOIL-009: Low automation potential."""
    if task.automation_potential == AutomationPotential.LOW and task.annual_hours > 50:
        report.findings.append(_make_finding("TOIL-009", task,
            description=f"'{task.name}' has low automation potential but uses {task.annual_hours:.0f}h/year"))
