"""Parse toil inventory YAML into ToilTask objects."""
import yaml
from .models import (
    ToilTask, ToilCategory, TaskFrequency, AutomationPotential,
)

CATEGORY_MAP = {
    "manual_intervention": ToilCategory.MANUAL_INTERVENTION,
    "repetitive_task": ToilCategory.REPETITIVE_TASK,
    "incident_response": ToilCategory.INCIDENT_RESPONSE,
    "deployment": ToilCategory.DEPLOYMENT,
    "scaling": ToilCategory.SCALING,
    "monitoring": ToilCategory.MONITORING,
    "access_management": ToilCategory.ACCESS_MANAGEMENT,
    "data_management": ToilCategory.DATA_MANAGEMENT,
    "certificate_rotation": ToilCategory.CERTIFICATE_ROTATION,
    "configuration": ToilCategory.CONFIGURATION,
}

FREQUENCY_MAP = {
    "hourly": TaskFrequency.HOURLY,
    "daily": TaskFrequency.DAILY,
    "weekly": TaskFrequency.WEEKLY,
    "monthly": TaskFrequency.MONTHLY,
    "quarterly": TaskFrequency.QUARTERLY,
    "ad_hoc": TaskFrequency.AD_HOC,
}

POTENTIAL_MAP = {
    "high": AutomationPotential.HIGH,
    "medium": AutomationPotential.MEDIUM,
    "low": AutomationPotential.LOW,
    "none": AutomationPotential.NONE,
}


def parse_inventory(yaml_content: str) -> list[ToilTask]:
    """Parse toil inventory YAML into ToilTask objects."""
    data = yaml.safe_load(yaml_content)
    if not data:
        return []
    tasks_data = data if isinstance(data, list) else data.get("tasks", [])
    tasks = []
    for entry in tasks_data:
        cat_str = entry.get("category", "manual_intervention").lower()
        freq_str = entry.get("frequency", "weekly").lower()
        pot_str = entry.get("automation_potential", "medium").lower()
        task = ToilTask(
            name=entry.get("name", ""),
            description=entry.get("description", ""),
            category=CATEGORY_MAP.get(cat_str, ToilCategory.MANUAL_INTERVENTION),
            frequency=FREQUENCY_MAP.get(freq_str, TaskFrequency.WEEKLY),
            duration_minutes=float(entry.get("duration_minutes", 30)),
            team_size=entry.get("team_size", 1),
            is_automatable=entry.get("is_automatable", True),
            automation_potential=POTENTIAL_MAP.get(pot_str, AutomationPotential.MEDIUM),
            automation_effort_hours=float(entry.get("automation_effort_hours", 40)),
            owner=entry.get("owner", ""),
            service=entry.get("service", ""),
            labels=entry.get("labels", {}),
        )
        tasks.append(task)
    return tasks
