from __future__ import annotations

import csv
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional

from .normalize import norm_mac


@dataclass
class GatewayDef:
    mac: str
    name: str = ""
    id: str = ""


def _sniff_delimiter(sample: str) -> str:
    # fallback robusto: prova a sniffare, altrimenti ';'
    try:
        return csv.Sniffer().sniff(sample, delimiters=";,\t").delimiter
    except Exception:
        return ";"


def load_gateway_features_csv(path: str) -> List[GatewayDef]:
    """
    Carica gateway.csv.
    Attesi header: mac;name;id  (name/id opzionali)
    Normalizza MAC in formato canonico 'AA:BB:CC:DD:EE:FF'
    """
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(f"gateway csv not found: {path}")

    txt = p.read_text(encoding="utf-8", errors="ignore")
    delim = _sniff_delimiter(txt[:2048])

    rows: List[GatewayDef] = []
    with p.open("r", encoding="utf-8", errors="ignore", newline="") as f:
        rd = csv.DictReader(f, delimiter=delim)
        for r in rd:
            # accetta anche varianti tipo 'MAC' o 'gw_mac'
            mac_raw = r.get("mac") or r.get("MAC") or r.get("gw_mac") or r.get("gateway_mac")
            if not mac_raw:
                continue
            mac = norm_mac(mac_raw)
            if not mac:
                continue

            name = (r.get("name") or r.get("NAME") or "").strip()
            gid = (r.get("id") or r.get("ID") or "").strip()
            rows.append(GatewayDef(mac=mac, name=name, id=gid))

    return rows


# ---------------------------------------------------------------------------
# BACKWARD COMPATIBILITY
# main.py si aspetta load_gateway_csv() -> List[GatewayDef]
# ---------------------------------------------------------------------------
def load_gateway_csv(path: str) -> List[GatewayDef]:
    """
    Alias compatibile per vecchie versioni.
    """
    return load_gateway_features_csv(path)
