"""Calculo de status de manutencao (OK / vencendo / vencido) por truck x item."""
from datetime import datetime, timedelta, timezone


def _remaining(current, baseline, interval):
    if current is None or baseline is None or interval is None:
        return None
    next_due = baseline + interval
    return next_due - current, next_due


def compute_item_status(truck, item, last_record):
    """
    truck: instancia Truck (com odometer_miles, engine_hours)
    item: instancia MaintenanceItem (com interval_miles/hours/days e warnings)
    last_record: ultima MaintenanceRecord para esse truck+item, ou None
    """
    if last_record is None:
        return {
            "status": "sem_registro",
            "remaining_miles": None,
            "remaining_hours": None,
            "remaining_days": None,
            "next_due_miles": None,
            "next_due_hours": None,
            "next_due_date": None,
        }

    remaining_miles = next_due_miles = None
    if item.interval_miles:
        r = _remaining(truck.odometer_miles, last_record.mileage_at_service, item.interval_miles)
        if r:
            remaining_miles, next_due_miles = r

    remaining_hours = next_due_hours = None
    if item.interval_hours:
        r = _remaining(truck.engine_hours, last_record.hours_at_service, item.interval_hours)
        if r:
            remaining_hours, next_due_hours = r

    remaining_days = next_due_date = None
    if item.interval_days:
        service_date = last_record.service_date
        if service_date.tzinfo is None:
            service_date = service_date.replace(tzinfo=timezone.utc)
        next_due_date = service_date + timedelta(days=item.interval_days)
        now = datetime.now(timezone.utc)
        remaining_days = (next_due_date - now).days

    dimensions_applicable = any(v is not None for v in (remaining_miles, remaining_hours, remaining_days))
    if not dimensions_applicable:
        status = "sem_configuracao"
    else:
        is_overdue = (
            (remaining_miles is not None and remaining_miles < 0)
            or (remaining_hours is not None and remaining_hours < 0)
            or (remaining_days is not None and remaining_days < 0)
        )
        is_warning = (
            (remaining_miles is not None and 0 <= remaining_miles <= item.warning_miles)
            or (remaining_hours is not None and 0 <= remaining_hours <= item.warning_hours)
            or (remaining_days is not None and 0 <= remaining_days <= item.warning_days)
        )
        if is_overdue:
            status = "vencido"
        elif is_warning:
            status = "vencendo"
        else:
            status = "ok"

    return {
        "status": status,
        "remaining_miles": remaining_miles,
        "remaining_hours": remaining_hours,
        "remaining_days": remaining_days,
        "next_due_miles": next_due_miles,
        "next_due_hours": next_due_hours,
        "next_due_date": next_due_date,
    }


STATUS_PRIORITY = {"vencido": 3, "vencendo": 2, "sem_registro": 1, "sem_configuracao": 1, "ok": 0}


def worst_status(statuses):
    if not statuses:
        return "sem_configuracao"
    return max(statuses, key=lambda s: STATUS_PRIORITY.get(s, 0))
