import os
import subprocess
from django.core.management.base import BaseCommand
from django.conf import settings

class Command(BaseCommand):
    help = 'Check PHP limits by running a PHP script.'

    def handle(self, *args, **kwargs):
        # Define the path to the PHP script located at the management/commands level
        php_script_path = os.path.join(
            os.path.dirname(__file__), 'scripts', 'phpinfo_check.php'
        )

        # Ensure the script exists
        if not os.path.isfile(php_script_path):
            self.stdout.write(self.style.ERROR(f"PHP script not found at {php_script_path}"))
            return

        # Run the PHP script and capture the output
        try:
            result = subprocess.run(
                ['php', php_script_path],
                capture_output=True,
                text=True,
                check=True
            )

            # Extract relevant PHP configurations from the output
            output = result.stdout
            self.stdout.write("PHP Configuration Details:\n")
            for line in output.splitlines():
                if any(key in line for key in ['upload_max_filesize', 'post_max_size', 'memory_limit']):
                    self.stdout.write(line)

        except subprocess.CalledProcessError as e:
            self.stdout.write(self.style.ERROR("Failed to run PHP script."))
            self.stdout.write(self.style.ERROR(f"Error: {e}"))
            if e.output:
                self.stdout.write(e.output)
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"An unexpected error occurred: {e}"))
