"""Logica de sincronizacao com o Geotab: cria/atualiza trucks e cache de odometro/horas."""
from datetime import datetime, timezone

from dateutil import parser as date_parser

from .database import SessionLocal
from .models import Truck, MaintenanceItem, SyncLog
from .geotab_client import get_geotab_client

DEFAULT_MAINTENANCE_ITEMS = [
    # "vencendo" comeca com 80% do intervalo consumido (20% restante)
    dict(name="Troca de óleo do motor", interval_miles=20000, interval_hours=500, warning_miles=4000, warning_hours=100),
    dict(name="Filtro de combustível", interval_miles=20000, warning_miles=4000),
    dict(name="Lubrificação (graxa)", interval_miles=5000, warning_miles=1000),
    dict(name="Inspeção DOT", interval_days=365, warning_days=73),
    dict(name="Ajuste de válvulas", interval_miles=None),
    dict(name="Inspeção dos freios", interval_miles=None),
    dict(name="Óleo de transmissão e diferenciais", interval_miles=None),
]


def seed_default_maintenance_items(db):
    if db.query(MaintenanceItem).count() > 0:
        return
    for item_data in DEFAULT_MAINTENANCE_ITEMS:
        db.add(MaintenanceItem(**item_data))
    db.commit()


def _parse_dt(value):
    if value is None:
        return None
    if isinstance(value, datetime):
        return value
    return date_parser.isoparse(value)


def run_sync() -> dict:
    """Executa uma sincronizacao completa. Retorna resumo do resultado."""
    db = SessionLocal()
    log = SyncLog(started_at=datetime.now(timezone.utc))
    db.add(log)
    db.commit()
    db.refresh(log)

    try:
        client = get_geotab_client()
        devices = client.get_devices()
        device_ids = {d["id"] for d in devices}
        status_data = client.get_odometer_miles_and_engine_hours(device_ids)

        updated = 0
        for device in devices:
            truck = db.query(Truck).filter_by(geotab_device_id=device["id"]).one_or_none()
            if truck is None:
                truck = Truck(geotab_device_id=device["id"], name=device.get("name", device["id"]))
                db.add(truck)
            else:
                truck.name = device.get("name", truck.name)
            truck.vin = device.get("vehicleIdentificationNumber") or truck.vin
            truck.serial_number = device.get("serialNumber") or truck.serial_number
            truck.license_plate = device.get("licensePlate") or truck.license_plate

            info = status_data.get(device["id"])
            if info:
                if info["odometer_miles"] is not None:
                    truck.odometer_miles = info["odometer_miles"]
                    truck.odometer_date = _parse_dt(info["odometer_date"])
                if info["engine_hours"] is not None:
                    truck.engine_hours = info["engine_hours"]
                    truck.engine_hours_date = _parse_dt(info["engine_hours_date"])
            truck.last_synced_at = datetime.now(timezone.utc)
            updated += 1

        seed_default_maintenance_items(db)

        db.commit()
        log.finished_at = datetime.now(timezone.utc)
        log.success = True
        log.trucks_updated = updated
        log.message = f"{updated} truck(s) sincronizado(s)."
        db.commit()
        return {"success": True, "trucks_updated": updated}

    except Exception as exc:
        db.rollback()
        log.finished_at = datetime.now(timezone.utc)
        log.success = False
        log.message = str(exc)
        db.commit()
        return {"success": False, "error": str(exc)}
    finally:
        db.close()
