"""
Tests for Issue #132: Basic HTML Generation and Rendering

This module tests the core functionality of the md-render command for
client-side markdown rendering with JavaScript.
"""

import pytest
import tempfile
import os
from pathlib import Path
from unittest.mock import patch, MagicMock
import json
import re

# Add project root to path for imports
import sys
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from markitect.plugins.builtin.markdown_commands import MarkdownCommandsPlugin


class TestIssue132BasicRendering:
    """Test basic HTML generation and markdown rendering functionality."""

    def setup_method(self):
        """Set up test environment."""
        self.plugin = MarkdownCommandsPlugin()
        self.plugin.initialize()

        # Create temporary directory for test outputs
        self.temp_dir = tempfile.mkdtemp()

    def teardown_method(self):
        """Clean up test environment."""
        # Clean up temporary files
        import shutil
        shutil.rmtree(self.temp_dir, ignore_errors=True)

    def test_md_render_command_exists(self):
        """Test that md-render command is registered in plugin - Issue #132."""
        commands = self.plugin.get_commands()

        # Should include md-render command
        assert 'md-render' in commands

        # Command should be callable
        md_render_cmd = commands['md-render']
        assert callable(md_render_cmd)

    def test_generate_basic_html_from_simple_markdown(self):
        """Test generating HTML from simple markdown content - Issue #132."""
        # Create test markdown content
        markdown_content = """# Test Document

This is a **test** document with some *italic* text and a [link](https://example.com).

## Section 2

- List item 1
- List item 2
- List item 3
"""

        # Create temporary input file
        input_file = Path(self.temp_dir) / "test.md"
        input_file.write_text(markdown_content)

        output_file = Path(self.temp_dir) / "output.html"

        # Test actual command execution
        from markitect.plugins.builtin.markdown_commands import md_render_command
        from click.testing import CliRunner

        runner = CliRunner()
        result = runner.invoke(md_render_command, [str(input_file), '--output', str(output_file)])

        # Should execute successfully
        assert result.exit_code == 0
        assert output_file.exists()

        # Should generate HTML file with content
        html_content = output_file.read_text()
        assert '<!DOCTYPE html>' in html_content
        assert '<title>Test Document</title>' in html_content

    def test_html_contains_embedded_markdown_payload(self):
        """Test that generated HTML contains markdown as JavaScript payload - Issue #132."""
        markdown_content = "# Simple Test\n\nThis is test content."

        input_file = Path(self.temp_dir) / "simple.md"
        input_file.write_text(markdown_content)

        output_file = Path(self.temp_dir) / "simple.html"

        # Test actual rendering
        from markitect.plugins.builtin.markdown_commands import md_render_command
        from click.testing import CliRunner

        runner = CliRunner()
        result = runner.invoke(md_render_command, [str(input_file), '--output', str(output_file)])

        assert result.exit_code == 0
        assert output_file.exists()

        html_content = output_file.read_text()

        # Should contain JavaScript with embedded markdown
        assert 'const markdownContent =' in html_content
        assert json.dumps(markdown_content) in html_content

        # Should contain script tag for rendering
        assert '<script' in html_content
        assert 'marked' in html_content.lower()

    def test_html_includes_javascript_markdown_parser(self):
        """Test that generated HTML includes JavaScript markdown parser - Issue #132."""
        markdown_content = "# Parser Test\n\nTesting parser inclusion."

        input_file = Path(self.temp_dir) / "parser_test.md"
        input_file.write_text(markdown_content)

        output_file = Path(self.temp_dir) / "parser_test.html"

        # Test actual rendering
        from markitect.plugins.builtin.markdown_commands import md_render_command
        from click.testing import CliRunner

        runner = CliRunner()
        result = runner.invoke(md_render_command, [str(input_file), '--output', str(output_file)])

        assert result.exit_code == 0
        assert output_file.exists()

        html_content = output_file.read_text()

        # Should include markdown parser (marked.js or similar)
        assert any(parser in html_content.lower() for parser in ['marked', 'markdown-it', 'showdown'])

        # Should include rendering logic
        assert 'DOMContentLoaded' in html_content or 'window.onload' in html_content

    def test_generated_html_is_valid_structure(self):
        """Test that generated HTML has valid document structure - Issue #132."""
        markdown_content = "# Structure Test\n\nTesting HTML structure."

        input_file = Path(self.temp_dir) / "structure.md"
        input_file.write_text(markdown_content)

        output_file = Path(self.temp_dir) / "structure.html"

        # Test actual rendering
        from markitect.plugins.builtin.markdown_commands import md_render_command
        from click.testing import CliRunner

        runner = CliRunner()
        result = runner.invoke(md_render_command, [str(input_file), '--output', str(output_file)])

        assert result.exit_code == 0
        assert output_file.exists()

        html_content = output_file.read_text()

        # Valid HTML5 document structure
        assert html_content.startswith('<!DOCTYPE html>')
        assert '<html' in html_content
        assert '<head>' in html_content
        assert '<body>' in html_content
        assert '</html>' in html_content

        # Should have content div for rendering
        assert 'id="markdown-content"' in html_content

    def test_handles_empty_markdown_file(self):
        """Test behavior with empty markdown file - Issue #132."""
        # Create empty markdown file
        input_file = Path(self.temp_dir) / "empty.md"
        input_file.write_text("")

        output_file = Path(self.temp_dir) / "empty.html"

        # Test actual rendering
        from markitect.plugins.builtin.markdown_commands import md_render_command
        from click.testing import CliRunner

        runner = CliRunner()
        result = runner.invoke(md_render_command, [str(input_file), '--output', str(output_file)])

        # Should handle empty file gracefully
        assert result.exit_code == 0
        assert output_file.exists()

        html_content = output_file.read_text()
        # Should still generate valid HTML structure
        assert '<!DOCTYPE html>' in html_content
        assert 'const markdownContent = "";' in html_content

    def test_handles_markdown_with_code_blocks(self):
        """Test handling markdown with code blocks - Issue #132."""
        markdown_content = """# Code Test

Here's some Python code:

```python
def hello_world():
    print("Hello, World!")
    return True
```

And some inline `code` too.
"""

        input_file = Path(self.temp_dir) / "code_test.md"
        input_file.write_text(markdown_content)

        output_file = Path(self.temp_dir) / "code_test.html"

        # Test actual rendering with code blocks
        from markitect.plugins.builtin.markdown_commands import md_render_command
        from click.testing import CliRunner

        runner = CliRunner()
        result = runner.invoke(md_render_command, [str(input_file), '--output', str(output_file)])

        assert result.exit_code == 0
        assert output_file.exists()

        html_content = output_file.read_text()

        # Should properly escape code content in JavaScript
        assert 'def hello_world' in html_content
        # Should handle backticks and quotes properly
        assert json.dumps(markdown_content) in html_content

    def test_cli_command_interface_exists(self):
        """Test that md-render CLI command interface exists - Issue #132."""
        from markitect.cli import cli

        # Should have md-render command registered
        assert 'md-render' in cli.commands

        cmd = cli.commands['md-render']
        assert cmd.name == 'md-render'
        assert cmd.help is not None
        assert 'markdown' in cmd.help.lower()