from __future__ import annotations

import csv
from pathlib import Path
from typing import Any, Dict, List, Sequence, Union

_FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r")


def csv_safe_cell(value: Any) -> str:
    s = "" if value is None else str(value)
    if s and s[0] in _FORMULA_PREFIXES:
        return "'" + s
    return s


def csv_safe_row(row: Dict[str, Any]) -> Dict[str, str]:
    return {k: csv_safe_cell(v) for k, v in row.items()}


def csv_safe_rows(rows: List[Dict[str, Any]]) -> List[Dict[str, str]]:
    return [csv_safe_row(r) for r in rows]


def write_csv(
    path: Union[str, Path],
    fieldnames: Sequence[str],
    rows: List[Dict[str, Any]],
) -> None:
    """Write CSV with utf-8-sig BOM and formula-injection safe cells."""
    out = Path(path)
    out.parent.mkdir(parents=True, exist_ok=True)
    with out.open("w", encoding="utf-8-sig", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(fieldnames))
        w.writeheader()
        w.writerows(csv_safe_rows(rows))
