"""Tests para dedup_duckdb_table_by_hash."""

from __future__ import annotations

import os
import tempfile

import duckdb
import pytest

from pipelines.dedup_duckdb_table_by_hash import dedup_duckdb_table_by_hash


def _make_test_db(path: str) -> None:
    """Create a test DuckDB with 5 rows: 3 unique data, 2 duplicates."""
    conn = duckdb.connect(path)
    conn.execute(
        """
        CREATE TABLE stories (
            run_id      VARCHAR,
            extracted_at TIMESTAMP,
            rank        INTEGER,
            title       VARCHAR,
            url         VARCHAR,
            points      INTEGER
        )
        """
    )
    conn.execute(
        """
        INSERT INTO stories VALUES
          ('run-001', '2026-05-16 10:00:00', 1, 'Story A', 'https://a.com', 100),
          ('run-001', '2026-05-16 10:00:00', 2, 'Story B', 'https://b.com', 200),
          ('run-001', '2026-05-16 10:00:00', 3, 'Story C', 'https://c.com', 300),
          ('run-002', '2026-05-16 10:30:00', 1, 'Story A', 'https://a.com', 100),
          ('run-002', '2026-05-16 10:30:00', 2, 'Story B', 'https://b.com', 200)
        """
    )
    conn.close()


def test_dedup_elimina_filas_duplicadas_y_conserva_unicas():
    """dedup elimina filas duplicadas y conserva unicas"""
    with tempfile.TemporaryDirectory() as tmpdir:
        db_path = os.path.join(tmpdir, "test.duckdb")
        _make_test_db(db_path)

        result = dedup_duckdb_table_by_hash(db_path, "stories")

        assert result["status"] == "ok", f"Expected ok, got: {result}"
        assert result["rows_before"] == 5
        assert result["rows_after"] == 3, f"Expected 3 unique rows, got {result['rows_after']}"
        assert result["dedup_removed"] == 2
        assert result["hash_column"] == "row_hash"
        assert result["duration_ms"] >= 0

        # Verify row_hash column exists and is populated
        conn = duckdb.connect(db_path)
        hashes = conn.execute("SELECT DISTINCT row_hash FROM stories").fetchall()
        conn.close()
        assert len(hashes) == 3, f"Expected 3 distinct hashes, got {len(hashes)}"
        # All hashes should be non-null
        assert all(h[0] is not None for h in hashes), "Some row_hash values are NULL"


def test_dedup_idempotente():
    """Running dedup twice leaves rows_after unchanged."""
    with tempfile.TemporaryDirectory() as tmpdir:
        db_path = os.path.join(tmpdir, "test.duckdb")
        _make_test_db(db_path)

        r1 = dedup_duckdb_table_by_hash(db_path, "stories")
        r2 = dedup_duckdb_table_by_hash(db_path, "stories")

        assert r1["status"] == "ok"
        assert r2["status"] == "ok"
        assert r2["rows_before"] == 3
        assert r2["rows_after"] == 3
        assert r2["dedup_removed"] == 0


def test_dedup_tabla_inexistente():
    """Returns status=error when table does not exist."""
    with tempfile.TemporaryDirectory() as tmpdir:
        db_path = os.path.join(tmpdir, "empty.duckdb")
        conn = duckdb.connect(db_path)
        conn.close()

        result = dedup_duckdb_table_by_hash(db_path, "nonexistent_table")
        assert result["status"] == "error"
        assert "nonexistent_table" in result["error"]


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
