"""Tests para load_folder_to_duckdb."""

import os
import sys

sys.path.insert(0, os.path.dirname(__file__))

import duckdb  # noqa: E402

from load_folder_to_duckdb import load_folder_to_duckdb  # noqa: E402


def _write_csv(path: str, header: str, rows: list[str]) -> None:
    with open(path, "w", encoding="utf-8") as f:
        f.write(header + "\n")
        for r in rows:
            f.write(r + "\n")


def test_carga_dos_csv_como_tablas(tmp_path):
    _write_csv(
        str(tmp_path / "ventas.csv"),
        "id,total",
        ["1,10.5", "2,20.0", "3,5.25"],
    )
    _write_csv(
        str(tmp_path / "clientes.csv"),
        "id,nombre",
        ["1,ana", "2,luis"],
    )
    db = tmp_path / "out.duckdb"
    res = load_folder_to_duckdb(str(tmp_path), str(db))

    assert res["status"] == "ok", res
    assert res["errors"] == []
    assert len(res["tables"]) == 2
    assert res["db_path"] == str(db)
    assert os.path.exists(str(db))

    by_name = {t["name"]: t for t in res["tables"]}
    assert by_name["ventas"]["n_rows"] == 3
    assert by_name["clientes"]["n_rows"] == 2

    # Verificar que las tablas existen realmente en la base.
    con = duckdb.connect(str(db), read_only=True)
    assert con.execute("SELECT count(*) FROM ventas").fetchone()[0] == 3
    assert con.execute("SELECT count(*) FROM clientes").fetchone()[0] == 2
    con.close()


def test_db_path_none_crea_temporal(tmp_path):
    _write_csv(str(tmp_path / "datos.csv"), "x", ["1", "2"])
    res = load_folder_to_duckdb(str(tmp_path))
    assert res["status"] == "ok", res
    assert res["db_path"]
    assert os.path.exists(res["db_path"])
    assert len(res["tables"]) == 1
    assert res["tables"][0]["n_rows"] == 2
    os.remove(res["db_path"])


def test_carpeta_vacia_es_ok_sin_tablas(tmp_path):
    db = tmp_path / "out.duckdb"
    res = load_folder_to_duckdb(str(tmp_path), str(db))
    assert res["status"] == "ok", res
    assert res["tables"] == []
    assert res["errors"] == []


def test_carpeta_inexistente_devuelve_status_error(tmp_path):
    res = load_folder_to_duckdb(str(tmp_path / "no_existe"))
    assert res["status"] == "error"
    assert "folder" in res["error"]
