"""Attachment downloader — fetch test case files from Jira tickets.

Downloads Excel (.xlsx) and CSV (.csv) attachments from a Jira issue
to a local temp directory for parsing.
"""

from __future__ import annotations

import logging
import tempfile
from pathlib import Path

import httpx

log = logging.getLogger("antiqa.jira")

TEST_CASE_EXTENSIONS = {".xlsx", ".csv", ".xls"}


class AttachmentDownloader:
    """Download test-case-related attachments from a Jira issue."""

    def __init__(self, jira_agent: "JiraAgent", download_dir: str | Path | None = None) -> None:  # noqa: F821
        from antiqa.jira.agent import JiraAgent  # deferred to avoid circular import

        self.agent: JiraAgent = jira_agent
        self.download_dir = Path(download_dir) if download_dir else Path(tempfile.mkdtemp(prefix="antiqa_"))
        self.download_dir.mkdir(parents=True, exist_ok=True)

    def get_test_case_attachments(self, issue_key: str) -> list[dict[str, str]]:
        """Return only the test-case-related attachments (Excel/CSV) from an issue."""
        all_attachments = self.agent.get_attachments(issue_key)
        return [
            att for att in all_attachments
            if self._is_test_case_file(att["filename"])
        ]

    def download_all(self, issue_key: str) -> list[Path]:
        """Download all test case files from a Jira issue. Returns list of local paths."""
        attachments = self.get_test_case_attachments(issue_key)
        if not attachments:
            log.info("No test case attachments found on %s", issue_key)
            return []

        downloaded: list[Path] = []
        for att in attachments:
            path = self._download_file(att)
            if path:
                downloaded.append(path)

        log.info("Downloaded %d test case file(s) from %s", len(downloaded), issue_key)
        return downloaded

    def _download_file(self, attachment: dict[str, str]) -> Path | None:
        """Download a single attachment to the local directory."""
        filename = attachment["filename"]
        content_url = attachment["content_url"]
        dest = self.download_dir / filename

        try:
            # Use the JIRA client's session for authenticated download
            session = self.agent.client._session
            response = session.get(content_url)
            response.raise_for_status()
            dest.write_bytes(response.content)
            log.info("Downloaded: %s (%s bytes)", filename, attachment.get("size", "?"))
            return dest
        except Exception as exc:
            log.error("Failed to download %s: %s", filename, exc)
            return None

    @staticmethod
    def _is_test_case_file(filename: str) -> bool:
        """Check if a filename looks like a test case file."""
        suffix = Path(filename).suffix.lower()
        return suffix in TEST_CASE_EXTENSIONS
