"""Tests for filingArchive class functionality."""

import lzma
import os
from unittest.mock import MagicMock, patch

from secbulkdownload.secfiling import filingArchive


class TestFilingArchiveInit:
    """Test filingArchive initialization."""

    def test_init_path_parsing(self, datadir: str) -> None:
        """Test that SEC filepath is correctly parsed."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        # Patch headerfile to avoid network calls
        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )

        # Verify local filename path structure
        expected_local = os.path.join(
            datadir, "filings", "0000320193", "0000320193-23-000077.txt.xz"
        )
        assert archive.localfilename == expected_local

    def test_init_url_construction(self, datadir: str) -> None:
        """Test that SEC URL is correctly constructed."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )

        expected_url = "https://www.sec.gov/Archives/edgar/data/0000320193/0000320193-23-000077.txt"
        assert archive.filingURL == expected_url

    def test_init_headerfile_created(self, datadir: str) -> None:
        """Test that headerfile instance is created during init."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {"TYPE": "10-K"}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )

            # Verify headerfile was called with correct args
            mock_headerfile.assert_called_once()
            assert archive.header == {"TYPE": "10-K"}


class TestCheckLocalFile:
    """Test local file checking."""

    def test_check_localfile_false_when_missing(self, datadir: str) -> None:
        """Test that check_localfile returns False for missing file."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )

        assert archive.check_localfile() is False

    def test_check_localfile_true_when_exists(self, datadir: str) -> None:
        """Test that check_localfile returns True for existing file."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        # Create the cached file
        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(b"test content"))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )

        assert archive.check_localfile() is True


class TestGetFilingArchive:
    """Test get_filingArchive document extraction."""

    def _create_mock_archive_content(self) -> bytes:
        """Create mock SEC filing archive content."""
        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
ACCESSION NUMBER:		0000320193-23-000077
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>apple10k.htm
<DESCRIPTION>Annual Report
<TEXT>
<html><body><h1>Apple Inc. Annual Report</h1></body></html>
</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-21
<SEQUENCE>2
<FILENAME>exhibit21.htm
<DESCRIPTION>Subsidiaries
<TEXT>
<html><body><p>Subsidiaries list</p></body></html>
</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-101.INC
<SEQUENCE>3
<FILENAME>apple-2023.xml
<DESCRIPTION>XBRL Instance
<TEXT>
<xbrl><context id="c1"></context></xbrl>
</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""
        return content.encode("latin-1")

    def test_document_extraction(self, datadir: str) -> None:
        """Test that documents are correctly extracted from archive."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        # Create cached file
        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_mock_archive_content()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

        # Verify documents were extracted
        assert len(archive.files) == 3
        filenames = [f.filename for f in archive.files]
        assert "apple10k.htm" in filenames
        assert "exhibit21.htm" in filenames
        assert "apple-2023.xml" in filenames

    def test_document_metadata(self, datadir: str) -> None:
        """Test that document metadata is correctly extracted."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_mock_archive_content()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

        # Get first document (10-K)
        doc = archive.files[0]
        assert doc.filename == "apple10k.htm"
        assert doc.type == "10-K"
        assert doc.sequence == "1"
        assert doc.description == "Annual Report"
        assert "Apple Inc. Annual Report" in doc.body

    def test_document_ordering(self, datadir: str) -> None:
        """Test that documents are ordered by sequence."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_mock_archive_content()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

        # Verify ordering by sequence
        sequences = [f.sequence for f in archive.files]
        assert sequences == ["1", "2", "3"]

    def test_acceptance_datetime_extraction(self, datadir: str) -> None:
        """Test that acceptance-datetime is correctly extracted."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_mock_archive_content()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

        # Acceptance datetime should be first 14 chars
        assert archive.acceptance_datetime == "20230101120000"


class TestDocumentTypeFiltering:
    """Test document type filtering."""

    def _create_multi_type_archive(self) -> bytes:
        """Create archive with multiple document types."""
        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>report.htm
<DESCRIPTION>Annual Report
<TEXT>
<html><body>10-K Content</body></html>
</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-21
<SEQUENCE>2
<FILENAME>exhibit21.htm
<DESCRIPTION>Subsidiaries
<TEXT>
<html><body>EX-21 Content</body></html>
</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-32
<SEQUENCE>3
<FILENAME>exhibit32.txt
<DESCRIPTION>Certification
<TEXT>
EX-32 Certification Content
</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""
        return content.encode("latin-1")

    def test_filter_single_type(self, datadir: str) -> None:
        """Test filtering by a single document type."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_multi_type_archive()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive(document_types="EX-21")

        # Should only include EX-21
        assert len(archive.files) == 1
        assert archive.files[0].type == "EX-21"

    def test_filter_list_of_types(self, datadir: str) -> None:
        """Test filtering by a list of document types."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_multi_type_archive()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive(document_types=["10-K", "EX-32"])

        # Should include 10-K and EX-32
        assert len(archive.files) == 2
        types = [f.type for f in archive.files]
        assert "10-K" in types
        assert "EX-32" in types
        assert "EX-21" not in types

    def test_filter_all_types(self, datadir: str) -> None:
        """Test getting all document types."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_multi_type_archive()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive(document_types="ALL")

        # Should include all 3 documents
        assert len(archive.files) == 3


class TestTextOnlyFiltering:
    """Test text_only filtering."""

    def _create_mixed_extension_archive(self) -> bytes:
        """Create archive with mixed file extensions."""
        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>report.htm
<DESCRIPTION>HTML Report
<TEXT>
HTML content
</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-99
<SEQUENCE>2
<FILENAME>data.pdf
<DESCRIPTION>PDF Document
<TEXT>
PDF content (binary)
</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-101
<SEQUENCE>3
<FILENAME>instance.XML
<DESCRIPTION>XBRL Instance
<TEXT>
XBRL content
</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>GRAPHIC
<SEQUENCE>4
<FILENAME>logo.jpg
<DESCRIPTION>Logo Image
<TEXT>
binary image data
</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""
        return content.encode("latin-1")

    def test_text_only_excludes_binary(self, datadir: str) -> None:
        """Test that text_only=True excludes binary files."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_mixed_extension_archive()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive(text_only=True)

        # Should only include htm and XML files
        filenames = [f.filename for f in archive.files]
        assert "report.htm" in filenames
        assert "instance.XML" in filenames
        assert "data.pdf" not in filenames
        assert "logo.jpg" not in filenames

    def test_text_only_false_includes_all(self, datadir: str) -> None:
        """Test that text_only=False includes all files."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(self._create_mixed_extension_archive()))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive(text_only=False)

        # Should include all 4 documents
        assert len(archive.files) == 4


class TestCacheHitMiss:
    """Test cache hit and miss scenarios."""

    def test_cache_hit_uses_local_file(self, datadir: str) -> None:
        """Test that cached file is used when available."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        # Create cached file
        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")

        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>report.htm
<DESCRIPTION>Report
<TEXT>Content</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(content.encode("latin-1")))

        with (
            patch("secbulkdownload.secfiling.headerfile") as mock_headerfile,
            patch("secbulkdownload.secfiling.fetch_sec_file") as mock_fetch,
        ):
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

            # fetch_sec_file should not be called since file exists
            mock_fetch.assert_not_called()

    def test_cache_miss_fetches_from_sec(self, datadir: str) -> None:
        """Test that file is fetched from SEC when not cached."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>report.htm
<DESCRIPTION>Report
<TEXT>Content</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""

        with (
            patch("secbulkdownload.secfiling.headerfile") as mock_headerfile,
            patch("secbulkdownload.secfiling.fetch_sec_file") as mock_fetch,
        ):
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            # Return tuple (localpath, data) as expected by _fetch_archive
            mock_fetch.return_value = (
                "/some/path.xz",
                content.encode("latin-1"),
            )

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

            # fetch_sec_file should be called
            mock_fetch.assert_called_once()


class TestGetFilenames:
    """Test get_filenames method."""

    def test_get_filenames_returns_list(self, datadir: str) -> None:
        """Test that get_filenames returns correct list."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")

        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>file1.htm
<DESCRIPTION>A
<TEXT>X</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-21
<SEQUENCE>2
<FILENAME>file2.txt
<DESCRIPTION>B
<TEXT>Y</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(content.encode("latin-1")))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

        filenames = archive.get_filenames()
        assert filenames == ["file1.htm", "file2.txt"]

    def test_get_filenames_empty_before_extraction(self, datadir: str) -> None:
        """Test that get_filenames returns empty list before extraction."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )

        # Before calling get_filingArchive
        assert archive.get_filenames() == []


class TestGetDocumentsByType:
    """Test get_documents_by_type method."""

    def test_get_documents_by_type(self, datadir: str) -> None:
        """Test filtering documents by type after extraction."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")

        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>report.htm
<DESCRIPTION>A
<TEXT>X</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-21
<SEQUENCE>2
<FILENAME>ex21.htm
<DESCRIPTION>B
<TEXT>Y</TEXT>
</DOCUMENT>
<DOCUMENT>
<TYPE>EX-21
<SEQUENCE>3
<FILENAME>ex21b.htm
<DESCRIPTION>C
<TEXT>Z</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(content.encode("latin-1")))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

        ex21_docs = archive.get_documents_by_type("EX-21")
        assert len(ex21_docs) == 2
        assert all(d.type == "EX-21" for d in ex21_docs)

    def test_get_documents_by_type_no_match(self, datadir: str) -> None:
        """Test get_documents_by_type returns empty list for no matches."""
        sec_filepath = "edgar/data/0000320193/0000320193-23-000077.txt"

        filings_dir = os.path.join(datadir, "filings", "0000320193")
        os.makedirs(filings_dir, exist_ok=True)
        cached_file = os.path.join(filings_dir, "0000320193-23-000077.txt.xz")

        content = """<SEC-DOCUMENT>0000320193-23-000077.txt : 20230101
<SEC-HEADER>0000320193-23-000077.hdr.sgml : 20230101
<ACCEPTANCE-DATETIME>20230101120000
</SEC-HEADER>
<DOCUMENT>
<TYPE>10-K
<SEQUENCE>1
<FILENAME>report.htm
<DESCRIPTION>A
<TEXT>X</TEXT>
</DOCUMENT>
</SEC-DOCUMENT>"""
        with open(cached_file, "wb") as f:
            f.write(lzma.compress(content.encode("latin-1")))

        with patch("secbulkdownload.secfiling.headerfile") as mock_headerfile:
            mock_hdr = MagicMock()
            mock_hdr.get_headerDict.return_value = {}
            mock_headerfile.return_value = mock_hdr

            archive = filingArchive(
                sec_filepath, datadir=datadir, user_agent="Test Co test@test.com"
            )
            archive.get_filingArchive()

        result = archive.get_documents_by_type("EX-99")
        assert result == []
