import subprocess
from django.shortcuts import render
from django.contrib.auth.decorators import user_passes_test
from django.views.decorators.cache import never_cache

@never_cache
@user_passes_test(lambda u: u.is_superuser)
def terminal_viewer(request):
    output = ""
    command = ""
    
    if request.method == "POST":
        command = request.POST.get("command", "")
        if command:
            try:
                # Execute the command in the project directory
                result = subprocess.run(
                    command, 
                    shell=True, 
                    capture_output=True, 
                    text=True, 
                    cwd="/home/orkoworo/idealogy/api",
                    timeout=30
                )
                output = result.stdout + result.stderr
                if not output:
                    output = "[Command executed successfully with no output]"
            except subprocess.TimeoutExpired:
                output = "Error: Command timed out after 30 seconds."
            except Exception as e:
                output = f"Error: {str(e)}"

    return render(request, 'exams/dev/terminal_viewer.html', {
        'output': output,
        'command': command
    })
