"""Tests para csv_to_parquet_duckdb."""
from __future__ import annotations

import tempfile
from pathlib import Path

import pytest


def test_convierte_csv_a_parquet_y_duckdb_puede_leerlo():
    """convierte csv a parquet y duckdb puede leerlo"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from core.csv_to_parquet_duckdb import csv_to_parquet_duckdb
    import duckdb

    with tempfile.TemporaryDirectory() as tmpdir:
        csv_path = Path(tmpdir) / "test.csv"
        parquet_path = Path(tmpdir) / "test.parquet"

        csv_path.write_text("nombre,lat,lon\nMadrid,40.4,-3.7\nBarcelona,41.3,2.1\n")

        result = csv_to_parquet_duckdb(csv_path, parquet_path)
        assert result is True
        assert parquet_path.exists()
        assert parquet_path.stat().st_size > 0

        # Verify duckdb can read it back
        con = duckdb.connect()
        df = con.execute(f"SELECT * FROM read_parquet('{parquet_path}')").df()
        con.close()
        assert df.shape == (2, 3)
        assert set(df.columns) == {"nombre", "lat", "lon"}


def test_overwrite_False_no_sobreescribe_parquet_existente():
    """overwrite=False no sobreescribe parquet existente"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from core.csv_to_parquet_duckdb import csv_to_parquet_duckdb

    with tempfile.TemporaryDirectory() as tmpdir:
        csv_path = Path(tmpdir) / "test.csv"
        parquet_path = Path(tmpdir) / "test.parquet"

        csv_path.write_text("a,b\n1,2\n")
        # Create existing parquet with known content
        parquet_path.write_bytes(b"existing content")
        original_size = parquet_path.stat().st_size

        result = csv_to_parquet_duckdb(csv_path, parquet_path, overwrite=False)
        assert result is False
        # File must remain unchanged
        assert parquet_path.stat().st_size == original_size
