"""Utilitários pequenos de normalização usados em todo o planejador."""

from __future__ import annotations

import math
import re
from datetime import date, datetime
from pathlib import Path
from typing import Any

import pandas as pd


def normalizar_texto(valor: Any) -> str:
    if valor is None or (isinstance(valor, float) and math.isnan(valor)):
        return ""
    return re.sub(r"\s+", " ", str(valor).strip()).upper()


def parse_bool(valor: Any) -> bool:
    return normalizar_texto(valor) in {"TRUE", "T", "1", "SIM", "S", "YES", "Y", "VERDADEIRO"}


def parse_data(valor: Any) -> date:
    texto = normalizar_texto(valor).lower()
    if texto in {"", "hoje", "today", "sysdate"}:
        return date.today()
    return pd.to_datetime(valor).date()


def parse_data_hora(valor: Any) -> pd.Timestamp:
    if valor is None or str(valor).strip() == "":
        return pd.NaT
    return pd.to_datetime(valor, errors="coerce")


def parse_horas(valor: Any) -> float | None:
    if valor is None or (isinstance(valor, float) and math.isnan(valor)):
        return None
    if isinstance(valor, (int, float)):
        return float(valor)
    texto = str(valor).strip().replace(",", ".")
    if texto == "":
        return None
    if ":" in texto:
        partes = texto.split(":")
        try:
            return float(partes[0]) + float(partes[1]) / 60
        except (ValueError, IndexError):
            return None
    try:
        return float(texto)
    except ValueError:
        return None


def clean_columns(df: pd.DataFrame) -> pd.DataFrame:
    df = df.copy()
    df.columns = [
        normalizar_texto(c)
        .lower()
        .replace("º", "")
        .replace("ç", "c")
        .replace("ã", "a")
        .replace("á", "a")
        .replace("é", "e")
        .replace("í", "i")
        .replace("ó", "o")
        .replace("ú", "u")
        .replace(" ", "_")
        .replace(".", "")
        for c in df.columns
    ]
    return df


def read_csv(path: Path, columns: list[str]) -> pd.DataFrame:
    if not path.exists():
        return pd.DataFrame(columns=columns)
    df = pd.read_csv(path)
    for col in columns:
        if col not in df.columns:
            df[col] = pd.NA
    return df[columns]
