"""
Unit tests for RecordBuilder.build_raw_text_records.

Tests the raw text record building functionality including:
- Row concatenation
- Row number = -1 for raw text
- Empty table handling
- Content structure
"""

import pytest
from uuid import uuid4

from src.extraction_v2.html_table_extractor import HtmlTable
from src.extraction_v2.record_builder import (
    RecordBuilder,
    build_raw_text_records_from_table,
)


class TestBuildRawTextRecords:
    """Test build_raw_text_records method."""

    def test_build_raw_text_records_concatenates_rows(self):
        """Test that multiple rows are concatenated with newlines."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[
                ["First line of text"],
                ["Second line of text"],
                ["Third line of text"],
            ],
            sheet_name="Sheet1",
            table_index=0,
            row_count=3,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id, "TestSheet")

        assert len(records) == 1
        assert records[0]["content"]["text"] == "First line of text\nSecond line of text\nThird line of text"

    def test_build_raw_text_records_sets_row_minus_one(self):
        """Test that row number is set to -1 for raw text records."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[["Some text content"]],
            sheet_name="Sheet1",
            table_index=5,
            row_count=1,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id, "TestSheet")

        assert len(records) == 1
        assert records[0]["_source"]["row"] == -1
        assert records[0]["_source"]["table_id"] == 5

    def test_build_raw_text_records_skips_empty(self):
        """Test that empty tables return empty list."""
        builder = RecordBuilder()
        document_id = uuid4()

        # Table with only empty rows
        table = HtmlTable(
            html="<table>...</table>",
            rows=[[""], ["   "], [""]],
            sheet_name="Sheet1",
            table_index=0,
            row_count=3,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id)

        assert records == []

    def test_build_raw_text_records_filters_empty_rows(self):
        """Test that empty rows are filtered but non-empty are kept."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[
                ["First line"],
                [""],
                ["Second line"],
                ["   "],
                ["Third line"],
            ],
            sheet_name="Sheet1",
            table_index=0,
            row_count=5,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id)

        assert len(records) == 1
        assert records[0]["content"]["text"] == "First line\nSecond line\nThird line"

    def test_build_raw_text_records_source_metadata(self):
        """Test that source metadata is correctly set."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[["Text content"]],
            sheet_name="OriginalSheet",
            table_index=3,
            row_count=1,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id, "CustomSheet")

        assert len(records) == 1
        source = records[0]["_source"]
        assert source["document_id"] == str(document_id)
        assert source["sheet"] == "CustomSheet"  # Custom sheet name takes precedence
        assert source["row"] == -1
        assert source["table_id"] == 3

    def test_build_raw_text_records_uses_table_sheet_name(self):
        """Test that table sheet name is used if no custom name provided."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[["Text content"]],
            sheet_name="TableSheetName",
            table_index=0,
            row_count=1,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id)

        assert records[0]["_source"]["sheet"] == "TableSheetName"

    def test_build_raw_text_records_default_sheet_name(self):
        """Test that 'Unknown' is used when no sheet name available."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[["Text content"]],
            sheet_name=None,
            table_index=0,
            row_count=1,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id)

        assert records[0]["_source"]["sheet"] == "Unknown"

    def test_build_raw_text_records_single_row(self):
        """Test single row raw text."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[["Only one line of content"]],
            sheet_name="Sheet1",
            table_index=0,
            row_count=1,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id)

        assert len(records) == 1
        assert records[0]["content"]["text"] == "Only one line of content"

    def test_build_raw_text_records_strips_whitespace(self):
        """Test that whitespace is stripped from row content."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[
                ["  Line with leading spaces  "],
                ["\tTabbed content\t"],
            ],
            sheet_name="Sheet1",
            table_index=0,
            row_count=2,
            col_count=1,
        )

        records = builder.build_raw_text_records(table, document_id)

        assert records[0]["content"]["text"] == "Line with leading spaces\nTabbed content"

    def test_build_raw_text_records_empty_rows_list(self):
        """Test table with empty rows list."""
        builder = RecordBuilder()
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[],
            sheet_name="Sheet1",
            table_index=0,
            row_count=0,
            col_count=0,
        )

        records = builder.build_raw_text_records(table, document_id)

        assert records == []


class TestBuildRawTextRecordsConvenienceFunction:
    """Test convenience function for building raw text records."""

    def test_build_raw_text_records_from_table(self):
        """Test build_raw_text_records_from_table convenience function."""
        document_id = uuid4()

        table = HtmlTable(
            html="<table>...</table>",
            rows=[["Text content"]],
            sheet_name="Sheet1",
            table_index=0,
            row_count=1,
            col_count=1,
        )

        records = build_raw_text_records_from_table(table, document_id, "TestSheet")

        assert len(records) == 1
        assert records[0]["content"]["text"] == "Text content"
        assert records[0]["_source"]["sheet"] == "TestSheet"
        assert records[0]["_source"]["row"] == -1


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