from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import AnsibleJob
from .forms import AnsibleJobForm
import subprocess
import tempfile
import os

def run_ansible_job(request, job):
    user = request.user
    decrypted_key = ""

    if user.encrypted_private_key:
        try:
            decrypted_key = user.decrypt_private_key().strip().replace("\r", "")
        except Exception as e:
            job.result = f"SSH 키 복호화 오류: {str(e)}"
            job.status = 'FAILED'
            job.save()
            return

    job.status = 'RUNNING'
    job.save()

    try:
        private_key = decrypted_key
        playbook_file = tempfile.NamedTemporaryFile(delete=False, mode="w", newline='')
        inventory_file = tempfile.NamedTemporaryFile(delete=False, mode="w", newline='')
        private_key_file = tempfile.NamedTemporaryFile(delete=False, mode="w", newline='')

        try:
            playbook_file.write(job.playbook_content.strip())
            playbook_file.close()

            inventory_file.write(job.inventory_content.strip())
            inventory_file.close()

            private_key_file.write(f"{private_key}\n")
            private_key_file.close()

            os.chmod(private_key_file.name, 0o600)

            command = [
                "ansible-playbook", playbook_file.name,
                "-i", inventory_file.name,
                "--private-key", private_key_file.name,
                # "-vvv"
            ]

            result = subprocess.run(command, capture_output=True, text=True)
            job.result = result.stdout
            job.status = 'SUCCESS' if result.returncode == 0 else 'FAILED'
        finally:
            os.remove(playbook_file.name)
            os.remove(inventory_file.name)
            os.remove(private_key_file.name)

    except Exception as e:
        job.result = f"오류 발생: {str(e)}"
        job.status = 'FAILED'

    job.save()


@login_required
def create_ansible_job(request):
    if request.method == 'POST':
        form = AnsibleJobForm(request.POST)
        if form.is_valid():
            job = form.save(commit=False)
            job.owner = request.user
            job.status = 'PENDING'
            job.save()
            return redirect('ansible_manager:job_list')
    else:
        form = AnsibleJobForm()
    return render(request, 'ansible_manager/create_job.html', {'form': form})

@login_required
def edit_ansible_job(request, job_id):
    job = get_object_or_404(AnsibleJob, id=job_id, owner=request.user)
    if request.method == 'POST':
        form = AnsibleJobForm(request.POST, instance=job)
        if form.is_valid():
            job = form.save(commit=False)
            job.owner = request.user
            job.status = 'PENDING'
            job.save()
            # return redirect('ansible_manager:job_detail', job_id=job.id)
            return redirect('ansible_manager:job_list')
    else:
        form = AnsibleJobForm(instance=job)
    return render(request, 'ansible_manager/edit_job.html', {'form': form, 'job': job})

@login_required
def job_list(request):
    jobs = AnsibleJob.objects.filter(owner=request.user).order_by('-created_at')
    return render(request, 'ansible_manager/job_list.html', {'jobs': jobs})


@login_required
def run_job(request, job_id):
    job = get_object_or_404(AnsibleJob, id=job_id, owner=request.user)
    run_ansible_job(request, job)
    return redirect('ansible_manager:job_detail', job_id=job.id)


@login_required
def job_detail(request, job_id):
    job = get_object_or_404(AnsibleJob, id=job_id, owner=request.user)
    return render(request, 'ansible_manager/job_detail.html', {'job': job})


@login_required
def delete_job(request, job_id):
    job = get_object_or_404(AnsibleJob, id=job_id, owner=request.user)
    job.delete()
    return redirect('ansible_manager:job_list')


def notice(request):
    return render(request, "ansible_manager/notice.html", {})
