"""
LibreOffice setup and validation for E2E testing.

Handles LibreOffice installation, configuration, and validation
for headless operation in GitHub Actions environment.
"""

import subprocess
import structlog

logger = structlog.get_logger(__name__)


def install_libreoffice() -> bool:
    """
    Install LibreOffice headless in Ubuntu environment.

    Returns:
        bool: True if installation successful, False otherwise.
    """
    try:
        logger.info("Starting LibreOffice installation")

        # Update package lists
        update_cmd = ["sudo", "apt-get", "update"]
        update_result = subprocess.run(
            update_cmd, capture_output=True, text=True, timeout=120, check=True
        )
        logger.debug("Package lists updated", stdout=update_result.stdout[:100])

        # Install LibreOffice
        install_cmd = ["sudo", "apt-get", "install", "-y", "libreoffice"]
        install_result = subprocess.run(
            install_cmd, capture_output=True, text=True, timeout=300, check=True
        )
        logger.info(
            "LibreOffice installation completed", stdout=install_result.stdout[:100]
        )

        return True

    except subprocess.CalledProcessError as e:
        logger.error(
            "LibreOffice installation failed", returncode=e.returncode, stderr=e.stderr
        )
        return False
    except subprocess.TimeoutExpired:
        logger.error("LibreOffice installation timed out")
        return False
    except Exception as e:
        logger.error("Unexpected error during LibreOffice installation", error=str(e))
        return False


def validate_headless_mode() -> bool:
    """
    Validate LibreOffice headless mode functionality.

    Returns:
        bool: True if headless mode works, False otherwise.
    """
    try:
        logger.info("Validating LibreOffice headless mode")

        # Test LibreOffice version and headless capability
        version_cmd = ["libreoffice", "--headless", "--version"]
        version_result = subprocess.run(
            version_cmd, capture_output=True, text=True, timeout=30, check=True
        )

        version_info = version_result.stdout.strip()
        logger.info("LibreOffice headless validation successful", version=version_info)

        # Additional validation - test help command
        help_cmd = ["libreoffice", "--headless", "--help"]
        subprocess.run(help_cmd, capture_output=True, text=True, timeout=30, check=True)

        logger.debug("LibreOffice help command successful")
        return True

    except subprocess.CalledProcessError as e:
        logger.error(
            "LibreOffice headless validation failed",
            returncode=e.returncode,
            stderr=e.stderr,
        )
        return False
    except subprocess.TimeoutExpired:
        logger.error("LibreOffice headless validation timed out")
        return False
    except FileNotFoundError:
        logger.error("LibreOffice not found - installation may have failed")
        return False
    except Exception as e:
        logger.error("Unexpected error during LibreOffice validation", error=str(e))
        return False


def test_libreoffice_conversion() -> bool:
    """
    Test LibreOffice conversion capabilities with a simple file.

    Returns:
        bool: True if conversion test successful, False otherwise.
    """
    try:
        import tempfile
        import os

        logger.info("Testing LibreOffice conversion capabilities")

        with tempfile.TemporaryDirectory() as temp_dir:
            import zipfile

            # Build a minimal valid ODF document (ZIP-based format)
            test_file = os.path.join(temp_dir, "test.odt")
            mimetype = b"application/vnd.oasis.opendocument.text"
            content_xml = b"""<?xml version="1.0" encoding="UTF-8"?>
<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
  xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
  <office:body><office:text>
    <text:p>Test document for LibreOffice validation</text:p>
  </office:text></office:body>
</office:document-content>"""
            manifest_xml = b"""<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
  <manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="/"/>
  <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
</manifest:manifest>"""

            with zipfile.ZipFile(test_file, "w", zipfile.ZIP_DEFLATED) as zf:
                # mimetype must be first entry, stored uncompressed
                zf.writestr(
                    zipfile.ZipInfo("mimetype"),
                    mimetype,
                    compress_type=zipfile.ZIP_STORED,
                )
                zf.writestr("content.xml", content_xml)
                zf.writestr("META-INF/manifest.xml", manifest_xml)

            # Test conversion to PDF
            output_file = os.path.join(temp_dir, "test.pdf")
            convert_cmd = [
                "libreoffice",
                "--headless",
                "--convert-to",
                "pdf",
                "--outdir",
                temp_dir,
                test_file,
            ]

            subprocess.run(
                convert_cmd, capture_output=True, text=True, timeout=60, check=True
            )

            # Verify PDF was created
            if os.path.exists(output_file):
                logger.info("LibreOffice conversion test successful")
                return True
            else:
                logger.error("LibreOffice conversion test failed - no output file")
                return False

    except subprocess.CalledProcessError as e:
        logger.error(
            "LibreOffice conversion test failed",
            returncode=e.returncode,
            stderr=e.stderr,
        )
        return False
    except Exception as e:
        logger.error(
            "Unexpected error during LibreOffice conversion test", error=str(e)
        )
        return False


def get_libreoffice_info() -> dict:
    """
    Get LibreOffice installation information.

    Returns:
        dict: Information about LibreOffice installation.
    """
    info = {
        "installed": False,
        "version": None,
        "headless_supported": False,
        "conversion_supported": False,
    }

    try:
        # Check if LibreOffice is installed
        version_cmd = ["libreoffice", "--version"]
        version_result = subprocess.run(
            version_cmd, capture_output=True, text=True, timeout=10, check=True
        )

        info["installed"] = True
        info["version"] = version_result.stdout.strip()

        # Check headless support
        info["headless_supported"] = validate_headless_mode()

        # Check conversion support
        info["conversion_supported"] = test_libreoffice_conversion()

        logger.info("LibreOffice information gathered", info=info)

    except Exception as e:
        logger.debug("LibreOffice not available or not working", error=str(e))

    return info
