import os
import platform

from django import get_version as django_version
from django.contrib import messages
from django.db.models import Count, Q
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone

from .forms import PostizInstallBriefForm
from .models import PostizInstallBrief


SETUP_STEPS = [
    {
        "title": "Install the runtime",
        "description": "Get Node.js and the selected package manager onto the VM before cloning Postiz.",
    },
    {
        "title": "Wire prerequisite services",
        "description": "Confirm PostgreSQL, Redis, and Temporal are reachable before the first app boot.",
    },
    {
        "title": "Bootstrap the repository",
        "description": "Fill the .env file, install packages, push Prisma schema changes, and start the dev processes.",
    },
]


def base_context(request):
    host_name = request.get_host().lower()
    agent_brand = "AppWizzy" if host_name == "appwizzy.com" else "Flatlogic"
    now = timezone.now()
    stats = PostizInstallBrief.objects.aggregate(
        total=Count("id"),
        ready=Count(
            "id",
            filter=Q(postgres_ready=True, redis_ready=True, temporal_ready=True),
        ),
    )
    return {
        "project_name": "Postiz Native Setup Studio",
        "agent_brand": agent_brand,
        "django_version": django_version(),
        "python_version": platform.python_version(),
        "current_time": now,
        "host_name": host_name,
        "project_description": os.getenv("PROJECT_DESCRIPTION", ""),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
        "brief_stats": stats,
        "setup_steps": SETUP_STEPS,
    }


def build_blueprint(brief):
    prerequisites = [
        {
            "title": "Node runtime",
            "ready": True,
            "detail": f"Use {brief.node_version} with {brief.package_manager} for dependency management.",
        },
        {
            "title": "PostgreSQL",
            "ready": brief.postgres_ready,
            "detail": "Prepare DATABASE_URL before copying .env.example to .env.",
        },
        {
            "title": "Redis",
            "ready": brief.redis_ready,
            "detail": "Queue workers expect REDIS_URL on the VM.",
        },
        {
            "title": "Temporal stack",
            "ready": brief.temporal_ready,
            "detail": "Point TEMPORAL_ADDRESS at the Temporal service before starting dev workflows.",
        },
    ]

    env_lines = [
        'DATABASE_URL="postgresql://postiz-user:password@localhost:5432/postiz-db-local"',
        'REDIS_URL="redis://localhost:6379"',
        'TEMPORAL_ADDRESS="localhost:7233"',
        f'FRONTEND_URL="{brief.public_url}"',
        'NEXT_PUBLIC_BACKEND_URL="http://127.0.0.1:3000"',
        'BACKEND_INTERNAL_URL="http://127.0.0.1:3000"',
    ]

    command_plan = [
        "git clone https://github.com/gitroomhq/postiz-app.git",
        "pnpm install",
        "pnpm run prisma-db-push",
        "pnpm run dev",
    ]

    return {
        "prerequisites": prerequisites,
        "env_lines": env_lines,
        "command_plan": command_plan,
    }


def home(request):
    context = base_context(request)
    context.update(
        {
            "recent_briefs": PostizInstallBrief.objects.all()[:3],
        }
    )
    return render(request, "core/index.html", context)


def brief_create(request):
    if request.method == "POST":
        form = PostizInstallBriefForm(request.POST)
        if form.is_valid():
            brief = form.save()
            messages.success(request, "Install brief saved. Review the generated blueprint below.")
            return redirect("brief_detail", pk=brief.pk)
    else:
        form = PostizInstallBriefForm()

    context = base_context(request)
    context.update(
        {
            "form": form,
        }
    )
    return render(request, "core/brief_form.html", context)


def brief_list(request):
    context = base_context(request)
    context.update(
        {
            "briefs": PostizInstallBrief.objects.all(),
        }
    )
    return render(request, "core/brief_list.html", context)


def brief_detail(request, pk):
    brief = get_object_or_404(PostizInstallBrief, pk=pk)
    blueprint = build_blueprint(brief)
    context = base_context(request)
    context.update(
        {
            "brief": brief,
            "blueprint": blueprint,
        }
    )
    return render(request, "core/brief_detail.html", context)
