import pytest
import json
import os
import sys
import tempfile

# Add the parent directory to the path so we can import the script
# This is needed because pytest runs from the root directory but the script
# is in init-container/scripts/, and we need to import it
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Import the module we're testing
import generate_install_plugin_script as plugin_script


class TestGenerateInstallPluginScript:
    """Test the generate_install_plugin_script.py functionality"""

    def test_wget_with_curl_fallback_default_behavior(self):
        """Test default behavior: wget first with curl fallback"""
        plugins_data = {
            "ConfluentHubPlugins": None,
            "RemoteURLPlugins": [
                {
                    "Name": "kafka-connect-jdbc",
                    "ArchivePath": "https://example.com/plugin.zip",
                    "Checksum": "abc123def456",
                    "ExtraArgs": "",
                    "WgetExtraArgs": "",
                    "CurlExtraArgs": "",
                    "ForceCurl": False
                }
            ]
        }

        with tempfile.TemporaryDirectory() as tmpdir:
            plugins_file = os.path.join(tmpdir, "plugins.json")
            output_file = os.path.join(tmpdir, "install.sh")

            with open(plugins_file, 'w') as f:
                json.dump(plugins_data, f)

            # Generate the script using our function
            plugin_script.generate_install_script(plugins_file, output_file)

            # Read and verify the generated script
            with open(output_file, 'r') as f:
                script_content = f.read()

            # Assertions
            assert "if ! wget" in script_content, "wget command not found"
            assert "curl --max-redirs 0" in script_content, "curl fallback not found"
            assert "wget failed, falling back to curl" in script_content, "fallback message not found"

    def test_force_curl_behavior(self):
        """Test force curl behavior (skips wget)"""
        plugins_data = {
            "ConfluentHubPlugins": None,
            "RemoteURLPlugins": [
                {
                    "Name": "kafka-connect-spooldir",
                    "ArchivePath": "https://artifactory.example.com/plugin.zip",
                    "Checksum": "xyz789",
                    "ExtraArgs": "",
                    "WgetExtraArgs": "",
                    "CurlExtraArgs": "--user myuser:mypass",
                    "ForceCurl": True
                }
            ]
        }

        with tempfile.TemporaryDirectory() as tmpdir:
            plugins_file = os.path.join(tmpdir, "plugins.json")
            output_file = os.path.join(tmpdir, "install.sh")

            with open(plugins_file, 'w') as f:
                json.dump(plugins_data, f)

            plugin_script.generate_install_script(plugins_file, output_file)

            with open(output_file, 'r') as f:
                script_content = f.read()

            # Assertions
            assert "Using curl (force curl enabled)" in script_content, "Force curl message not found"
            assert "if ! wget" not in script_content, "wget should not be used when force curl is enabled"
            assert "curl --max-redirs 0" in script_content, "curl command not found"
            assert "--user myuser:mypass" in script_content, "Curl extra args not included"

    def test_multiple_plugins_mixed_settings(self):
        """Test multiple plugins with different settings"""
        plugins_data = {
            "ConfluentHubPlugins": [
                {
                    "Name": "confluentinc/kafka-connect-datagen:0.5.0",
                    "ExtraArgs": "--no-prompt"
                }
            ],
            "RemoteURLPlugins": [
                {
                    "Name": "plugin1",
                    "ArchivePath": "https://example.com/plugin1.zip",
                    "Checksum": "checksum1",
                    "ExtraArgs": "",
                    "WgetExtraArgs": "--timeout=30",
                    "CurlExtraArgs": "",
                    "ForceCurl": False
                },
                {
                    "Name": "plugin2",
                    "ArchivePath": "https://example.com/plugin2.zip",
                    "Checksum": "checksum2",
                    "ExtraArgs": "",
                    "WgetExtraArgs": "",
                    "CurlExtraArgs": "--insecure",
                    "ForceCurl": True
                }
            ]
        }

        with tempfile.TemporaryDirectory() as tmpdir:
            plugins_file = os.path.join(tmpdir, "plugins.json")
            output_file = os.path.join(tmpdir, "install.sh")

            with open(plugins_file, 'w') as f:
                json.dump(plugins_data, f)

            plugin_script.generate_install_script(plugins_file, output_file)

            with open(output_file, 'r') as f:
                script_content = f.read()

            # Assertions
            assert "confluent connect plugin install confluentinc/kafka-connect-datagen:0.5.0" in script_content
            assert "plugin1" in script_content
            assert "plugin2" in script_content
            assert "--timeout=30" in script_content
            assert "--insecure" in script_content
            assert script_content.count("===> Attempting to download") == 1  # Only plugin1 uses wget
            assert script_content.count("Using curl (force curl enabled)") == 1  # Only plugin2 forces curl

    def test_checksum_validation_present(self):
        """Test that checksum validation is included in the generated script"""
        plugins_data = {
            "ConfluentHubPlugins": None,
            "RemoteURLPlugins": [
                {
                    "Name": "test-plugin",
                    "ArchivePath": "https://example.com/plugin.zip",
                    "Checksum": "abc123def456abc123def456",
                    "ExtraArgs": "",
                    "WgetExtraArgs": "",
                    "CurlExtraArgs": "",
                    "ForceCurl": False
                }
            ]
        }

        with tempfile.TemporaryDirectory() as tmpdir:
            plugins_file = os.path.join(tmpdir, "plugins.json")
            output_file = os.path.join(tmpdir, "install.sh")

            with open(plugins_file, 'w') as f:
                json.dump(plugins_data, f)

            plugin_script.generate_install_script(plugins_file, output_file)

            with open(output_file, 'r') as f:
                script_content = f.read()

            # Verify checksum validation
            assert "sha512sum --check" in script_content
            assert ".sha512" in script_content
            assert "abc123def456abc123def456" in script_content

    def test_confluent_hub_plugin_only(self):
        """Test with only Confluent Hub plugins (no URL plugins)"""
        plugins_data = {
            "ConfluentHubPlugins": [
                {
                    "Name": "confluentinc/kafka-connect-s3:10.0.0",
                    "ExtraArgs": "--no-prompt"
                }
            ],
            "RemoteURLPlugins": None
        }

        with tempfile.TemporaryDirectory() as tmpdir:
            plugins_file = os.path.join(tmpdir, "plugins.json")
            output_file = os.path.join(tmpdir, "install.sh")

            with open(plugins_file, 'w') as f:
                json.dump(plugins_data, f)

            plugin_script.generate_install_script(plugins_file, output_file)

            with open(output_file, 'r') as f:
                script_content = f.read()

            assert "confluent connect plugin install confluentinc/kafka-connect-s3:10.0.0" in script_content
            assert "--no-prompt" in script_content
            # Should not have wget or curl commands
            assert "wget" not in script_content
            assert "curl" not in script_content
