import os
import sys

import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))

import report_pdf_exporter as rpe


def test_pdf_available_returns_bool():
    assert isinstance(rpe.pdf_available(), bool)


def test_export_requires_exactly_one_source(tmp_path):
    out = tmp_path / "x.pdf"
    with pytest.raises(ValueError):
        rpe.export_pdf(output_path=out)  # neither
    with pytest.raises(ValueError):
        rpe.export_pdf(html="<p>x</p>", html_path="x.html", output_path=out)  # both


def test_unavailable_is_runtime_error_subclass():
    assert issubclass(rpe.PDFExportUnavailable, RuntimeError)


def test_attempt_install_no_tty_returns_false_without_prompting():
    """Non-interactive (no TTY) must never prompt or install."""
    prompted = []

    def _input(_msg):
        prompted.append(_msg)
        return "y"

    assert rpe.attempt_install(_input=_input, _isatty=False) is False
    assert prompted == []  # never prompted


def test_attempt_install_declined_returns_false_without_installing():
    """User answering 'n' must not trigger any install."""
    assert rpe.attempt_install(_input=lambda _m: "n", _isatty=True) is False


def test_render_or_skip_if_unavailable(tmp_path):
    """Render a real PDF when Playwright + Chromium are present; skip otherwise."""
    out = tmp_path / "report.pdf"
    try:
        result = rpe.export_pdf(
            html="<html><body><h1>Hello</h1></body></html>",
            output_path=out,
        )
    except rpe.PDFExportUnavailable:
        pytest.skip("Playwright/Chromium not installed in this environment")
    assert result.exists()
    assert result.read_bytes()[:4] == b"%PDF"
