""" Helper per leggere i CSV sorgente ICR con DuckDB. Tutti i CSV ICR (eccetto gemma e osservatorio) hanno: - Riga 0: titolo descrittivo ("Estrazione Emesso ICR") - Riga 1: data elaborazione ("Elaborazione del 27/03/2026 07.17.08") - Riga 2: riga vuota - Riga 3+: header reali + dati Encoding: latin-1 (cp1252) Delimitatore: ; """ import duckdb def icr_csv(con: duckdb.DuckDBPyConnection, path: str, columns: list[str] | None = None) -> str: """ Restituisce una stringa SQL read_csv() per un file CSV ICR standard (skip=3). Uso: FROM {icr_csv(con, path)} AS src """ col_clause = '' if columns: quoted = ', '.join(f"'{c}'" for c in columns) col_clause = f", columns={{{quoted}}}" return ( f"read_csv('{path}', skip=3, delim=';', " f"quote='\"', escape='\"', strict_mode=false, all_varchar=true, " f"encoding='cp1252', header=true, ignore_errors=true{col_clause})" ) def gemma_csv(path: str) -> str: """CSV gemma: header sulla prima riga (nessun skip).""" return ( f"read_csv('{path}', skip=0, delim=';', " f"quote='\"', escape='\"', strict_mode=false, all_varchar=true, " f"encoding='cp1252', header=true, ignore_errors=true)" ) def osservatorio_csv(path: str, columns: list[str]) -> str: """ osservatorio.txt: nessun header nel file. I nomi colonne vengono passati esplicitamente. """ names = ', '.join(f"column{i:02d}: VARCHAR" for i in range(len(columns))) return ( f"read_csv('{path}', skip=0, delim=';', " f"quote='\"', escape='\"', strict_mode=false, all_varchar=true, " f"encoding='cp1252', header=false, ignore_errors=true, " f"names=[{', '.join(repr(c) for c in columns)}])" )