"""Tests for the 999 ACK serializer.

Mirrors ``test_parse_999.py``'s shape: build a ``ParseResult999`` in
memory, serialize it to X12, then re-parse the output and assert the
round-trip is stable.
"""
from __future__ import annotations

from datetime import date

import pytest

from cyclone.parsers.models import BatchSummary, Envelope
from cyclone.parsers.models_999 import (
    AcknowledgmentHeader,
    FunctionalGroupAck,
    ParseResult999,
    SetAcceptReject,
    SetFunctionalGroupResponse,
)
from cyclone.parsers.parse_999 import parse_999_text
from cyclone.parsers.serialize_999 import serialize_999


def _build_minimal_result() -> ParseResult999:
    return ParseResult999(
        envelope=Envelope(
            sender_id="RECEIVER",
            receiver_id="SUBMITTER",
            control_number="000000001",
            transaction_date=date(2024, 1, 1),
            implementation_guide="005010X231A1",
        ),
        functional_group_acks=[
            FunctionalGroupAck(
                ak1=AcknowledgmentHeader(
                    functional_id_code="HC", group_control_number="0001",
                ),
                received_count=1, accepted_count=1, rejected_count=0,
                ack_code="A",
            ),
        ],
        set_responses=[
            SetFunctionalGroupResponse(
                ak2=AcknowledgmentHeader(
                    functional_id_code="837", group_control_number="0001",
                ),
                set_control_number="0001",
                transaction_set_identifier="837",
                segment_errors=[],
                set_accept_reject=SetAcceptReject(code="A"),
            ),
        ],
        summary=BatchSummary(
            input_file="", total_claims=1, passed=1, failed=0,
        ),
    )


def test_serialize_999_envelope_segments():
    """Output must start with ISA* and end with IEA*."""
    text = serialize_999(_build_minimal_result())
    assert text.startswith("ISA*")
    assert text.rstrip("\n").endswith("~IEA*1*000000001~") or text.endswith("IEA*1*000000001~")
    # And the envelope layers are all present in order.
    assert "GS*HC*" in text
    assert "ST*999*" in text
    assert "AK1*HC*0001~" in text
    assert "AK2*837*0001~" in text
    assert "AK5*A~" in text
    assert "AK9*A*1*1*0~" in text
    assert "SE*" in text
    assert "GE*" in text
    assert "IEA*" in text


def test_serialize_999_minimal_round_trip():
    """Build a minimal result, serialize, re-parse — re-parsed result
    should match (modulo interchange_control_number differences)."""
    result = _build_minimal_result()
    text = serialize_999(result)
    re_parsed = parse_999_text(text, input_file="round_trip.txt")
    # envelope details
    assert re_parsed.envelope.control_number == "000000001"
    assert re_parsed.envelope.implementation_guide == "005010X231A1"
    # functional group ack
    assert len(re_parsed.functional_group_acks) == 1
    fg = re_parsed.functional_group_acks[0]
    assert fg.ack_code == "A"
    assert fg.received_count == 1
    assert fg.accepted_count == 1
    assert fg.rejected_count == 0
    assert fg.ak1.functional_id_code == "HC"
    assert fg.ak1.group_control_number == "0001"
    # set response
    assert len(re_parsed.set_responses) == 1
    s = re_parsed.set_responses[0]
    assert s.set_accept_reject.code == "A"
    assert s.transaction_set_identifier == "837"
    assert s.set_control_number == "0001"
    assert s.segment_errors == []


def test_serialize_999_ak9_counts_match_sets():
    """AK9's received/accepted/rejected counts equal the per-set AcceptReject codes.

    Builds a result with 3 sets: 2 accepted (A) + 1 rejected (R). The
    AK9 row must show received=3, accepted=2, rejected=1.
    """
    result = ParseResult999(
        envelope=Envelope(
            sender_id="R", receiver_id="S", control_number="000000001",
            transaction_date=date(2024, 1, 1),
            implementation_guide="005010X231A1",
        ),
        functional_group_acks=[
            FunctionalGroupAck(
                ak1=AcknowledgmentHeader(
                    functional_id_code="HC", group_control_number="0001",
                ),
                received_count=3, accepted_count=2, rejected_count=1,
                ack_code="P",  # partial
            ),
        ],
        set_responses=[
            SetFunctionalGroupResponse(
                ak2=AcknowledgmentHeader(
                    functional_id_code="837", group_control_number="1",
                ),
                set_control_number="1", transaction_set_identifier="837",
                segment_errors=[], set_accept_reject=SetAcceptReject(code="A"),
            ),
            SetFunctionalGroupResponse(
                ak2=AcknowledgmentHeader(
                    functional_id_code="837", group_control_number="2",
                ),
                set_control_number="2", transaction_set_identifier="837",
                segment_errors=[], set_accept_reject=SetAcceptReject(code="A"),
            ),
            SetFunctionalGroupResponse(
                ak2=AcknowledgmentHeader(
                    functional_id_code="837", group_control_number="3",
                ),
                set_control_number="3", transaction_set_identifier="837",
                segment_errors=[], set_accept_reject=SetAcceptReject(code="R"),
            ),
        ],
        summary=BatchSummary(input_file="", total_claims=3, passed=2, failed=1),
    )
    text = serialize_999(result)
    assert "AK9*P*3*2*1~" in text
    # Round-trip preserves the counts.
    re_parsed = parse_999_text(text, input_file="counts.txt")
    fg = re_parsed.functional_group_acks[0]
    assert fg.received_count == 3
    assert fg.accepted_count == 2
    assert fg.rejected_count == 1
    assert fg.ack_code == "P"


def test_serialize_999_emits_ak3_ak4_when_segment_errors_present():
    """A set with segment_errors must emit AK3 + AK4 segments in the
    serialized output, in order, after AK2 and before AK5.
    """
    from cyclone.parsers.models_999 import SegmentContext, SegmentError
    result = ParseResult999(
        envelope=Envelope(
            sender_id="R", receiver_id="S", control_number="000000001",
            transaction_date=date(2024, 1, 1),
            implementation_guide="005010X231A1",
        ),
        functional_group_acks=[
            FunctionalGroupAck(
                ak1=AcknowledgmentHeader(
                    functional_id_code="HC", group_control_number="0001",
                ),
                received_count=1, accepted_count=0, rejected_count=1,
                ack_code="R",
            ),
        ],
        set_responses=[
            SetFunctionalGroupResponse(
                ak2=AcknowledgmentHeader(
                    functional_id_code="837", group_control_number="0001",
                ),
                set_control_number="0001", transaction_set_identifier="837",
                segment_errors=[
                    SegmentError(
                        context=SegmentContext(
                            segment_id="CLM",
                            segment_position=12,
                            loop_id="2300",
                        ),
                        error_code="8",
                        element_position=4,
                        element_reference=None,
                    ),
                ],
                set_accept_reject=SetAcceptReject(code="R"),
            ),
        ],
        summary=BatchSummary(input_file="", total_claims=1, passed=0, failed=1),
    )
    text = serialize_999(result)
    # Order: AK2*837*0001~ AK3*CLM*12*2300~ AK4*4***8~ AK5*R~ AK9*R*1*0*1~ SE*
    assert "AK2*837*0001~" in text
    assert "AK3*CLM*12*2300~" in text
    assert "AK4*4***8~" in text
    # The AK4 must come AFTER the AK3 in the segment order.
    ak2_pos = text.index("AK2*")
    ak3_pos = text.index("AK3*")
    ak4_pos = text.index("AK4*")
    ak5_pos = text.index("AK5*")
    assert ak2_pos < ak3_pos < ak4_pos < ak5_pos
