"""Integration test for rxiv init -> rxiv pdf workflow.

This test ensures that manuscripts generated by `rxiv init` can be immediately
built successfully with `rxiv pdf`, fixing the critical user experience issue
where generated templates don't work out of the box.
"""

import subprocess

# Import the LaTeX check function from conftest
import sys
from pathlib import Path

import pytest

sys.path.append(str(Path(__file__).parent.parent))
from conftest import check_latex_available


@pytest.mark.xdist_group(name="init_build_workflow")
class TestInitBuildWorkflow:
    """Test that init-generated manuscripts build successfully."""

    @pytest.mark.skipif(not check_latex_available(), reason="LaTeX not available")
    def test_init_then_build_default_manuscript(self, temp_dir, monkeypatch):
        """Test that rxiv init creates a buildable manuscript (default path)."""
        monkeypatch.chdir(temp_dir)

        # Step 1: Initialize manuscript with non-interactive mode
        init_result = subprocess.run(
            ["rxiv", "init", "--no-interactive", "--force"],
            capture_output=True,
            text=True,
            timeout=60,
        )

        # Verify init succeeded
        assert init_result.returncode == 0, f"Init failed: {init_result.stderr}"

        # Verify expected files were created
        manuscript_dir = temp_dir / "MANUSCRIPT"
        assert manuscript_dir.exists(), "MANUSCRIPT directory not created"
        assert (manuscript_dir / "00_CONFIG.yml").exists(), "Config file not created"
        assert (manuscript_dir / "01_MAIN.md").exists(), "Main content file not created"
        assert (manuscript_dir / "02_SUPPLEMENTARY_INFO.md").exists(), "Supplementary info not created"
        assert (manuscript_dir / "03_REFERENCES.bib").exists(), "Bibliography not created"
        assert (manuscript_dir / "FIGURES").exists(), "FIGURES directory not created"
        assert (manuscript_dir / "FIGURES" / "Figure__example.mmd").exists(), "Example figure not created"

        # Step 2: Verify the figure reference uses .mmd (source) not .pdf (output)
        main_content = (manuscript_dir / "01_MAIN.md").read_text()
        assert "![](FIGURES/Figure__example.mmd)" in main_content, "Figure should reference .mmd source file"
        assert "{#fig:example}" in main_content, "Figure label missing"

        # Step 3: Build the manuscript (this should succeed without errors)
        build_result = subprocess.run(
            ["rxiv", "pdf", str(manuscript_dir)],
            capture_output=True,
            text=True,
            timeout=300,  # 5 minutes should be enough
        )

        # Verify build succeeded
        if build_result.returncode != 0:
            print(f"Build stdout: {build_result.stdout}")
            print(f"Build stderr: {build_result.stderr}")

        assert build_result.returncode == 0, f"Build failed: {build_result.stderr}"

        # Verify PDF was created
        pdf_file = manuscript_dir / "output" / "MANUSCRIPT.pdf"
        assert pdf_file.exists(), "PDF file was not generated"
        assert pdf_file.stat().st_size > 0, "Generated PDF is empty"

    @pytest.mark.skipif(not check_latex_available(), reason="LaTeX not available")
    def test_init_then_build_custom_manuscript(self, temp_dir, monkeypatch):
        """Test that init + build works with custom manuscript directory."""
        monkeypatch.chdir(temp_dir)

        custom_name = "MY_PAPER"

        # Step 1: Initialize manuscript with custom name
        init_result = subprocess.run(
            ["rxiv", "init", custom_name, "--no-interactive", "--force"],
            capture_output=True,
            text=True,
            timeout=60,
        )

        assert init_result.returncode == 0, f"Init failed: {init_result.stderr}"

        # Verify custom directory was created
        manuscript_dir = temp_dir / custom_name
        assert manuscript_dir.exists(), f"{custom_name} directory not created"

        # Step 2: Build the custom manuscript
        build_result = subprocess.run(
            ["rxiv", "pdf", str(manuscript_dir)],
            capture_output=True,
            text=True,
            timeout=300,
        )

        if build_result.returncode != 0:
            print(f"Custom build stdout: {build_result.stdout}")
            print(f"Custom build stderr: {build_result.stderr}")

        assert build_result.returncode == 0, f"Custom build failed: {build_result.stderr}"

        # Verify custom PDF was created with correct name
        pdf_file = manuscript_dir / "output" / f"{custom_name}.pdf"
        assert pdf_file.exists(), f"Custom PDF file {custom_name}.pdf not generated"

    @pytest.mark.skipif(not check_latex_available(), reason="LaTeX not available")
    def test_figure_generation_during_build(self, temp_dir, monkeypatch):
        """Test that the mermaid figure is properly generated during build."""
        monkeypatch.chdir(temp_dir)

        # Initialize manuscript
        subprocess.run(
            ["rxiv", "init", "--no-interactive", "--force"],
            capture_output=True,
            text=True,
            timeout=60,
        )

        manuscript_dir = temp_dir / "MANUSCRIPT"
        figures_dir = manuscript_dir / "FIGURES"

        # Verify source file exists but output doesn't initially
        source_file = figures_dir / "Figure__example.mmd"
        output_file = figures_dir / "Figure__example.pdf"

        assert source_file.exists(), "Mermaid source file not created"
        assert not output_file.exists(), "Output should not exist before build"

        # Build manuscript
        build_result = subprocess.run(
            ["rxiv", "pdf", str(manuscript_dir)],
            capture_output=True,
            text=True,
            timeout=300,
        )

        assert build_result.returncode == 0, f"Build failed: {build_result.stderr}"

        # Verify figure was generated during build
        assert output_file.exists(), "Figure was not generated during build"
        assert output_file.stat().st_size > 0, "Generated figure is empty"

    def test_validation_passes_after_init(self, temp_dir, monkeypatch):
        """Test that validation passes on init-generated manuscripts."""
        monkeypatch.chdir(temp_dir)

        # Initialize manuscript
        subprocess.run(
            ["rxiv", "init", "--no-interactive", "--force"],
            capture_output=True,
            text=True,
            timeout=60,
        )

        manuscript_dir = temp_dir / "MANUSCRIPT"

        # Run validation on the generated manuscript
        validation_result = subprocess.run(
            ["rxiv", "validate", str(manuscript_dir)],
            capture_output=True,
            text=True,
            timeout=120,
        )

        # Validation should pass without critical errors
        # (warnings are OK, but no errors that would prevent building)
        assert validation_result.returncode == 0, f"Validation failed: {validation_result.stderr}"
