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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
from __future__ import annotations

from datetime import UTC, date, datetime

import pytest

from recipe.parser import parse_complete_submission
from recipe.parser_header import (
    extract_submission_documents,
    parse_submission_header,
    select_ownership_document,
)
from recipe.parser_ownership_xml import OwnershipXMLParseError, parse_ownership_xml

from .conftest import complete_submission, index_entry


def test_complete_submission_header_and_document_selection(fixture_xml) -> None:
    submission = complete_submission(fixture_xml("form4_purchase"))
    header = parse_submission_header(submission)

    assert header.accession_number == "0000123456-26-000001"
    assert header.form_type == "4"
    assert header.filing_date == date(2026, 8, 24)
    assert header.period_of_report == date(2026, 8, 20)
    # August is daylight-saving time in New York: 15:30:45 EDT -> 19:30:45 UTC.
    assert header.accepted_at == datetime(2026, 8, 24, 19, 30, 45, tzinfo=UTC)

    documents = extract_submission_documents(submission)
    assert [document.filename for document in documents] == ["logo.gif", "ownership.xml"]
    selected = select_ownership_document(documents)
    assert selected is not None
    assert selected.filename == "ownership.xml"
    assert "ownershipDocument" in selected.text


def test_old_no_namespace_xml_keeps_historical_null_semantics(fixture_xml) -> None:
    parsed = parse_ownership_xml(fixture_xml("form4_2003"))

    assert parsed.document_type == "4"
    assert parsed.period_of_report == date(2003, 6, 30)
    assert parsed.issuer_cik == "0001067983"
    assert parsed.xml_schema_version == "3.0"
    assert len(parsed.owners) == 1
    assert parsed.owners[0].is_ten_percent_owner is True

    transaction = parsed.transactions[0]
    assert transaction.table_number == "I"
    assert transaction.filing_transaction_index == 1
    assert transaction.transaction_date == date(2003, 6, 30)
    assert transaction.transaction_code == "P"
    assert transaction.shares == 50.0
    assert transaction.price == 3.25
    assert transaction.shares_owned_after == 150.0
    assert transaction.is_10b5_1 is None


@pytest.mark.parametrize(
    ("case", "code", "acquired_disposed", "shares", "price", "plan_flag"),
    [
        ("form4_purchase", "P", "A", 1_000.0, 12.5, True),
        ("form4_sale", "S", "D", 200.0, 15.0, False),
    ],
)
def test_modern_namespaced_table_i_transactions(
    fixture_xml,
    case: str,
    code: str,
    acquired_disposed: str,
    shares: float,
    price: float,
    plan_flag: bool,
) -> None:
    parsed = parse_ownership_xml(fixture_xml(case))
    transaction = parsed.transactions[0]

    assert parsed.is_10b5_1 is plan_flag
    assert transaction.table_number == "I"
    assert transaction.transaction_code == code
    assert transaction.acquired_disposed == acquired_disposed
    assert transaction.shares == shares
    assert transaction.price == price
    assert transaction.is_derivative is False
    assert transaction.is_10b5_1 is plan_flag

    if case == "form4_purchase":
        assert parsed.issuer_trading_symbol_raw == "acme"
        assert parsed.owners[0].officer_title == "Chief Executive Officer"
        assert transaction.price_footnote_ids == ["F1"]
        assert transaction.footnote_ids == ["F1"]
        assert transaction.footnote_text == (
            "Weighted-average purchase price; source range retained verbatim."
        )


def test_table_ii_derivative_fields_do_not_leak_into_table_i_price(fixture_xml) -> None:
    parsed = parse_ownership_xml(fixture_xml("form4_derivative"))
    transaction = parsed.transactions[0]

    assert transaction.table_number == "II"
    assert transaction.is_derivative is True
    assert transaction.derivative_security_title == "Employee Stock Option"
    assert transaction.conversion_or_exercise_price == 5.0
    assert transaction.underlying_security_title == "Class A Common Stock"
    assert transaction.underlying_shares == 100.0
    assert transaction.exercise_date == date(2024, 1, 1)
    assert transaction.expiration_date == date(2034, 1, 1)
    assert transaction.derivative_price == 0.0
    assert transaction.derivative_owned_after == 900.0
    assert transaction.price is None
    assert transaction.shares_owned_after is None
    assert transaction.is_10b5_1 is None


def test_amendment_exposes_original_submission_date(fixture_xml) -> None:
    parsed = parse_ownership_xml(fixture_xml("form4_amendment", "amendment.xml"))

    assert parsed.document_type == "4/A"
    assert parsed.date_of_original_submission == date(2026, 1, 3)
    assert parsed.transactions[0].shares == 150.0


def test_multi_owner_filing_normalizes_one_transaction_notional_once(fixture_xml) -> None:
    submission = complete_submission(
        fixture_xml("form4_multi_owner"),
        accession_number="0000654321-26-000007",
        accepted_at="20260824110000",
        period_of_report="20260823",
    )
    parsed = parse_complete_submission(
        index_entry(accession_number="0000654321-26-000007"),
        submission,
        observed_at=datetime(2026, 8, 24, 16, 0, tzinfo=UTC),
    )

    assert parsed.filing.parse_status == "ok"
    assert parsed.filing.reporting_owner_count == 2
    assert len(parsed.owners) == 2
    assert all(owner.is_joint_filing for owner in parsed.owners)
    assert len(parsed.transactions) == 1

    transaction = parsed.transactions[0]
    assert transaction.reporting_owner_count == 2
    assert transaction.reporting_owner_ciks == ["0000888001", "0000888002"]
    assert transaction.reporting_owner_names == ["Jamie One", "Morgan Two"]
    assert transaction.insider_cik is None
    assert transaction.insider_name is None
    assert transaction.transaction_value == 200.0


def test_parser_isolates_malformed_filing_as_error_row() -> None:
    submission = complete_submission("<ownershipDocument><broken></ownershipDocument>")
    parsed = parse_complete_submission(
        index_entry(),
        submission,
        observed_at=datetime(2026, 8, 24, 20, 0, tzinfo=UTC),
    )

    assert parsed.filing.parse_status == "error"
    assert "XML" in (parsed.filing.parse_error or "")
    assert parsed.transactions == []
    assert parsed.owners == []


def test_unexpected_xml_root_is_rejected() -> None:
    with pytest.raises(OwnershipXMLParseError, match="unexpected root"):
        parse_ownership_xml("<notOwnershipDocument/>")


def test_mixed_10b5_1_filing_attributes_only_the_footnoted_row(fixture_xml) -> None:
    parsed = parse_ownership_xml(fixture_xml("form4_10b5_1"))

    assert parsed.is_10b5_1 is True
    sale, gift = parsed.transactions
    assert sale.transaction_code == "S"
    assert sale.footnote_ids == ["F1"]
    assert sale.is_10b5_1 is True
    # A document-level checkbox is not evidence about an unrelated row.
    assert gift.transaction_code == "G"
    assert gift.is_10b5_1 is None


def test_one_filing_can_mix_grant_withholding_exercise_and_sale(fixture_xml) -> None:
    submission = complete_submission(
        fixture_xml("form4_multiple_transactions"),
        accession_number="0000555000-26-000002",
        accepted_at="20260516143000",
        filed_on="20260516",
        period_of_report="20260515",
    )
    parsed = parse_complete_submission(
        index_entry(accession_number="0000555000-26-000002"),
        submission,
        observed_at=datetime(2026, 5, 16, 20, 0, tzinfo=UTC),
    )

    assert parsed.filing.parse_status == "ok"
    assert len(parsed.transactions) == 5

    classes = [(row.transaction_code, row.economic_type, row.signal_type) for row in parsed.transactions]
    assert classes == [
        ("A", "grant_or_award", "compensation"),
        ("F", "tax_withholding", "compensation"),
        ("M", "option_exercise", "derivative_exercise"),
        ("S", "open_market_sale", "discretionary_sell"),
        ("M", "option_exercise", "derivative_exercise"),
    ]

    # Identifiers stay stable and table-scoped, independent of mutable facts.
    assert [row.transaction_id for row in parsed.transactions] == [
        "0000555000-26-000002_I_001",
        "0000555000-26-000002_I_002",
        "0000555000-26-000002_I_003",
        "0000555000-26-000002_I_004",
        "0000555000-26-000002_II_001",
    ]

    sale = parsed.transactions[3]
    assert sale.transaction_value == pytest.approx(8_500 * 43.75)
    assert sale.primary_role == "CFO"

    grant = parsed.transactions[0]
    assert grant.price_quality == "zero"
    assert grant.transaction_value == 0.0

    derivative = parsed.transactions[4]
    assert derivative.is_derivative is True
    assert derivative.holding_change_quality == "derivative"
    assert derivative.holding_change_pct is None


def test_same_day_repeated_rows_do_not_produce_a_confident_holding_change(fixture_xml) -> None:
    parsed = parse_complete_submission(
        index_entry(accession_number="0000555000-26-000002"),
        complete_submission(
            fixture_xml("form4_multiple_transactions"),
            accession_number="0000555000-26-000002",
        ),
        observed_at=datetime(2026, 5, 16, 20, 0, tzinfo=UTC),
    )

    # Three Table I rows share 2026-05-15, security title, and ownership type,
    # so the position before each one is ambiguous.
    same_day = parsed.transactions[:3]
    assert all(row.holding_change_quality == "multiple_same_day_transactions" for row in same_day)
    assert all(row.holding_change_pct is None for row in same_day)

    # The lone 2026-05-16 sale is unambiguous and is measured.
    sale = parsed.transactions[3]
    assert sale.holding_change_quality == "ok"
    assert sale.holding_change_pct == pytest.approx(-8_500 / 58_500)


@pytest.mark.parametrize("wrap_xml", [True, False])
def test_ownership_xml_survives_the_sgml_xml_container(fixture_xml, wrap_xml: bool) -> None:
    """EDGAR nests ownership XML in `<TEXT><XML>`, putting the declaration on line 2.

    Every live Form 4 arrives this way. Submissions without the container must
    keep working, so both shapes are covered.
    """

    submission = complete_submission(fixture_xml("form4_purchase"), wrap_xml=wrap_xml)
    document = select_ownership_document(extract_submission_documents(submission))

    assert document is not None
    assert not document.text.lstrip().startswith("<XML>")
    assert document.text.lstrip().startswith("<?xml")

    parsed = parse_complete_submission(
        index_entry(), submission, observed_at=datetime(2026, 8, 24, 20, 0, tzinfo=UTC)
    )
    assert parsed.filing.parse_status == "ok"
    assert parsed.transactions[0].transaction_code == "P"


def test_truncated_xml_container_still_reaches_the_parser() -> None:
    """A submission cut off mid-document must be a visible parse error.

    Extraction must not drop it just because `</XML>` and `</TEXT>` are absent;
    a filing that vanished during extraction would leave no ledger row at all.
    """

    truncated = (
        "<SEC-HEADER>\n"
        "<ACCESSION-NUMBER>0000123456-26-000001\n"
        "<CONFORMED-SUBMISSION-TYPE>4\n"
        "<ACCEPTANCE-DATETIME>20260824153045\n"
        "<FILED-AS-OF-DATE>20260824\n"
        "</SEC-HEADER>\n"
        "<DOCUMENT>\n<TYPE>4\n<SEQUENCE>1\n<FILENAME>ownership.xml\n<TEXT>\n"
        '<XML>\n<?xml version="1.0"?>\n'
        "<ownershipDocument>\n  <documentType>4</documentType>\n"
        "</DOCUMENT>\n"
    )
    documents = extract_submission_documents(truncated)
    assert len(documents) == 1
    assert documents[0].text.lstrip().startswith("<?xml")

    parsed = parse_complete_submission(
        index_entry(), truncated, observed_at=datetime(2026, 8, 24, 20, 0, tzinfo=UTC)
    )
    assert parsed.filing.parse_status == "error"
    assert parsed.filing.parse_error


def test_edgar_fixed_width_wrapping_is_undone_before_parsing() -> None:
    """EDGAR hard-wraps dissemination lines at 1023 chars, cutting tags in half.

    Observed on 2004-2008 filings such as Tyson Foods 0000100493-04-000080,
    where "</footn" and "ote>" land on separate lines. Roughly 1% of 2004
    filings are unparseable without undoing this.
    """

    from recipe.parser_header import _DISSEMINATION_WRAP_WIDTH, _unwrap_dissemination_lines

    # The wrap must land mid-tag, so the fragment ends with a partial tag name.
    tail = "<securityTit"
    opening = "<ownershipDocument><pad>"
    padding = "x" * (_DISSEMINATION_WRAP_WIDTH - len(opening) - len("</pad>") - len(tail))
    first = f"{opening}{padding}</pad>{tail}"
    assert len(first) == _DISSEMINATION_WRAP_WIDTH
    assert first.endswith("<securityTit")
    wrapped = f"{first}\nle></ownershipDocument>"

    unwrapped = _unwrap_dissemination_lines(wrapped)
    assert "\n" not in unwrapped
    assert "<securityTitle>" in unwrapped, "the split tag name must be made whole again"


def test_hyphen_continuation_marker_is_removed_not_joined() -> None:
    """A continuation starting with a hyphen is prefixed with "- " by the feed.

    Seen on Alliant Energy 0000107832-04-000009, where "<value>2004" continues
    as "- -01-02</value>" and must reassemble as the date 2004-01-02, not
    "2004- -01-02".
    """

    from recipe.parser_header import _DISSEMINATION_WRAP_WIDTH, _unwrap_dissemination_lines

    head = "<transactionDate><value>2004"
    padding = "x" * (_DISSEMINATION_WRAP_WIDTH - len(head) - len("<pad></pad>"))
    first = f"<pad>{padding}</pad>{head}"
    assert len(first) == _DISSEMINATION_WRAP_WIDTH
    unwrapped = _unwrap_dissemination_lines(f"{first}\n- -01-02</value></transactionDate>")

    assert "<value>2004-01-02</value>" in unwrapped
    assert "- -01-02" not in unwrapped


def test_a_leading_hyphen_is_kept_when_no_wrap_precedes_it() -> None:
    """The marker is only meaningful straight after a wrapped fragment."""

    from recipe.parser_header import _DISSEMINATION_WRAP_WIDTH, _unwrap_dissemination_lines

    padded = "x" * _DISSEMINATION_WRAP_WIDTH
    text = f"<a>{padded}</a>\n<note>- bullet stays</note>"
    assert _unwrap_dissemination_lines(text).endswith("<note>- bullet stays</note>")


def test_unwrapping_leaves_normally_formatted_documents_alone(fixture_xml) -> None:
    from recipe.parser_header import _unwrap_dissemination_lines

    original = fixture_xml("form4_2003")
    assert _unwrap_dissemination_lines(original) == original


def test_a_wrapped_submission_parses_end_to_end() -> None:
    """The wrap must be undone during extraction, not left to the XML parser."""

    from recipe.parser_header import _DISSEMINATION_WRAP_WIDTH

    body = (
        '<?xml version="1.0"?><ownershipDocument><schemaVersion>X0201</schemaVersion>'
        "<documentType>4</documentType><periodOfReport>2004-01-23</periodOfReport>"
        "<issuer><issuerCik>0000100493</issuerCik><issuerName>TYSON FOODS INC</issuerName>"
        "<issuerTradingSymbol>TSN</issuerTradingSymbol></issuer>"
        "<reportingOwner><reportingOwnerId><rptOwnerCik>0000999001</rptOwnerCik>"
        "<rptOwnerName>Historic Owner</rptOwnerName></reportingOwnerId>"
        "<reportingOwnerRelationship><isDirector>1</isDirector></reportingOwnerRelationship>"
        "</reportingOwner><nonDerivativeTable><nonDerivativeTransaction>"
        "<securityTitle><value>Class A Common Stock</value></securityTitle>"
        "<transactionDate><value>2004-01-23</value></transactionDate>"
        "<transactionCoding><transactionCode>P</transactionCode></transactionCoding>"
        "<transactionAmounts><transactionShares><value>500</value></transactionShares>"
        "<transactionPricePerShare><value>13.25</value></transactionPricePerShare>"
        "<transactionAcquiredDisposedCode><value>A</value></transactionAcquiredDisposedCode>"
        "</transactionAmounts><postTransactionAmounts>"
        "<sharesOwnedFollowingTransaction><value>1500</value></sharesOwnedFollowingTransaction>"
        "</postTransactionAmounts><ownershipNature>"
        "<directOrIndirectOwnership><value>D</value></directOrIndirectOwnership>"
        "</ownershipNature></nonDerivativeTransaction></nonDerivativeTable>"
        "</ownershipDocument>"
    )
    wrapped = "\n".join(
        body[i : i + _DISSEMINATION_WRAP_WIDTH]
        for i in range(0, len(body), _DISSEMINATION_WRAP_WIDTH)
    )
    assert "\n" in wrapped, "the sample must actually exceed one wrapped line"

    parsed = parse_complete_submission(
        index_entry(),
        complete_submission(wrapped),
        observed_at=datetime(2004, 1, 26, 20, 0, tzinfo=UTC),
    )
    assert parsed.filing.parse_status == "ok"
    assert parsed.filing.issuer_name == "TYSON FOODS INC"
    assert parsed.transactions[0].transaction_code == "P"
    assert parsed.transactions[0].shares == 500.0


def test_a_header_timestamp_outranks_a_supplied_one(fixture_xml) -> None:
    """The feed supplies acceptance externally; a real header must still win."""

    submission = complete_submission(fixture_xml("form4_purchase"))
    supplied = datetime(2001, 1, 1, tzinfo=UTC)

    parsed = parse_complete_submission(
        index_entry(), submission,
        observed_at=datetime(2026, 8, 24, 20, 0, tzinfo=UTC),
        accepted_at_override=supplied,
        accepted_at_source="edgar_bulk_acceptance_corrected",
    )

    # The fixture's header says 15:30:45 EDT; the supplied value is ignored.
    assert parsed.filing.accepted_at == datetime(2026, 8, 24, 19, 30, 45, tzinfo=UTC)
    assert parsed.transactions[0].knowledge_date_source == "edgar_acceptance_datetime"