from src.services.export_service.export_normalizers import (
    ExcelValueSerializer,
    Form1RowNormalizer,
    Form3ReportRowNormalizer,
    SmetaRowNormalizer,
)


def test_form1_normalizer_merges_header_and_contract_fields():
    serializer = ExcelValueSerializer()
    normalizer = Form1RowNormalizer(serializer)
    row = {
        "header": {"section": "1.00.0.", "item_id": 1, "name": "A"},
        "contract_detail": {"reference": "DOG-1", "amount": 10},
        "plan": {"q1": 7},
    }

    normalized = normalizer.normalize(row)

    assert normalized["section"] == "1.00.0."
    assert normalized["item_id"] == 1
    assert normalized["name"] == "A"
    assert normalized["q1"] == 7
    assert normalized["contract"] == "DOG-1"
    assert normalized["contract_sum"] == 10
    assert "header" not in normalized


def test_smeta_normalizer_extracts_nested_values():
    normalizer = SmetaRowNormalizer()
    row = {
        "section_code": "1",
        "name": "SMETA row",
        "plan": {"support": {"q1": 5}, "total_year": 20},
        "approved": {"development": {"year": 8}},
    }

    normalized = normalizer.normalize(row)

    assert normalized["section_code"] == "1"
    assert normalized["name"] == "SMETA row"
    assert normalized["plan_support_q1"] == 5
    assert normalized["plan_total_year"] == 20
    assert normalized["approved_development_year"] == 8


def test_excel_value_serializer_formats_collections():
    serializer = ExcelValueSerializer()

    assert serializer.to_excel_value(["a", 1, None]) == "a, 1, "
    assert serializer.to_excel_value({"name": "X"}) == "X"
    assert serializer.to_excel_value({"k": {"nested": 1}}) == "k=1"


def test_form3_normalizer_flattens_quarters_and_totals_to_scalars():
    normalizer = Form3ReportRowNormalizer()
    row = {
        "header": {"section_code": "1.00.0.", "item_id": "R001", "name": "Строка"},
        "q1": {"quarter_actual": 10, "total_corr": 12},
        "q2": {"total_corr": 22},
        "q3": {"economy": 1.5},
        "q4": {"m1": 100},
        "totals": {"total_actual": 40, "economy": 2.1},
    }

    normalized = normalizer.normalize(row)

    assert normalized["section"] == "1.00.0."
    assert normalized["item_id"] == "R001"
    assert normalized["name"] == "Строка"
    assert normalized["q1"] == 10
    assert normalized["q2"] == 22
    assert normalized["q3"] == 1.5
    assert normalized["q4"] is None
    assert normalized["totals"] == 40
