"""Repositório CSV — mesmo schema do app JS (src/lib/csv.ts).

Colunas:
    data, tipo, escopo, categoria, valor, descricao, fornecedorCliente, meioPagamento
"""
import csv
import os
from typing import List, Tuple
from ..domain.models import Lancamento

COLS = [
    "data", "tipo", "escopo", "categoria", "valor",
    "descricao", "fornecedorCliente", "meioPagamento",
]


def salvar(path: str, lancamentos: List[Lancamento]) -> None:
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=COLS)
        w.writeheader()
        for l in lancamentos:
            w.writerow({
                "data": l.data,
                "tipo": l.tipo,
                "escopo": l.escopo,
                "categoria": l.categoria,
                "valor": l.valor,
                "descricao": l.descricao,
                "fornecedorCliente": l.fornecedor_cliente or "",
                "meioPagamento": l.meio_pagamento or "",
            })


def carregar(path: str) -> Tuple[List[Lancamento], List[str]]:
    """Retorna (lançamentos válidos, mensagens de erro por linha)."""
    if not os.path.exists(path):
        return [], []
    ok: List[Lancamento] = []
    erros: List[str] = []
    with open(path, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for i, row in enumerate(reader, start=2):
            try:
                ok.append(Lancamento(
                    data=row["data"].strip(),
                    tipo=row["tipo"].strip(),  # type: ignore[arg-type]
                    escopo=row["escopo"].strip(),  # type: ignore[arg-type]
                    categoria=row["categoria"].strip(),
                    valor=float(row["valor"]),
                    descricao=(row.get("descricao") or "").strip(),
                    fornecedor_cliente=(row.get("fornecedorCliente") or "").strip() or None,
                    meio_pagamento=(row.get("meioPagamento") or "").strip() or None,  # type: ignore[arg-type]
                ))
            except (KeyError, ValueError) as e:
                erros.append(f"Linha {i}: {e}")
    return ok, erros
