from __future__ import annotations

import unittest

from app.services.context_budgeting import (
    deduplicate_records,
    deduplicate_texts,
    limit_items,
    truncate_text,
)


class ContextBudgetingTest(unittest.TestCase):
    def test_deduplicate_texts_is_stable_on_normalized_content(self) -> None:
        items, metrics = deduplicate_texts(
            ["  Hallazgo importante  ", "hallazgo importante", "Otro hallazgo", ""]
        )

        self.assertEqual(items, ["Hallazgo importante", "Otro hallazgo"])
        self.assertEqual(metrics.input_count, 4)
        self.assertEqual(metrics.output_count, 2)
        self.assertEqual(metrics.duplicates_removed, 2)

    def test_truncate_text_applies_character_budget(self) -> None:
        value, metrics = truncate_text("ABCDEFGHIJ", max_chars=6)

        self.assertEqual(value, "ABCDEF")
        self.assertEqual(metrics.truncated_items, 1)
        self.assertEqual(metrics.truncated_chars, 4)

    def test_limit_items_preserves_original_order(self) -> None:
        items, metrics = limit_items(["a", "b", "c", "d"], max_items=2)

        self.assertEqual(items, ["a", "b"])
        self.assertEqual(metrics.input_count, 4)
        self.assertEqual(metrics.output_count, 2)

    def test_deduplicate_records_uses_custom_key_without_reordering(self) -> None:
        records, metrics = deduplicate_records(
            [
                {"page": 1, "extracto": "Texto A"},
                {"page": 1, "extracto": "texto a"},
                {"page": 2, "extracto": "Texto B"},
            ],
            key_fn=lambda item: f"{item['page']}|{item['extracto']}",
        )

        self.assertEqual(records, [{"page": 1, "extracto": "Texto A"}, {"page": 2, "extracto": "Texto B"}])
        self.assertEqual(metrics.output_count, 2)
