import io
import zipfile
from pathlib import Path
from unittest.mock import patch

import pytest

import server


def minimal_docx():
    output = io.BytesIO()
    with zipfile.ZipFile(output, 'w') as archive:
        archive.writestr('[Content_Types].xml', '<Types/>')
        archive.writestr('word/document.xml', '<w:document/>')
    return output.getvalue()


def test_validation_rejects_invalid_pdf():
    with pytest.raises(server.ConversionError, match='valid PDF'):
        server._validate_document('upload.pdf', b'not a PDF')


def test_validation_accepts_docx_container():
    server._validate_document('upload.docx', minimal_docx())


def test_conversion_returns_renderer_output():
    def fake_run(command, **kwargs):
        output_dir = Path(command[command.index('--outdir') + 1])
        output_dir.joinpath('input.pdf').write_bytes(b'%PDF-1.4 converted')

        class Completed:
            returncode = 0
            stderr = b''

        return Completed()

    with patch.object(server, '_find_libreoffice', return_value='soffice'):
        with patch.object(server.subprocess, 'run', side_effect=fake_run):
            result = server._run_document_conversion('source.docx', minimal_docx(), 'pdf')

    assert result.startswith(b'%PDF-')