from django.views.generic import TemplateView
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
import json
import logging

logger = logging.getLogger(__name__)


class MiniAppsListView(TemplateView):
    template_name = 'links/mini_apps/list.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Define mini apps with their info
        mini_apps = [
            {
                'name': 'Image Gallery',
                'description': 'A beautiful fullscreen image slideshow application with smooth transitions and auto-play functionality.',
                'url': 'mini-apps-image-gallery',
                'thumbnail': 'https://plus.unsplash.com/premium_photo-1748027749836-b2755867ee62?w=400&h=300&fit=crop',
                'icon': 'fas fa-images',
                'color': '#3498db'
            },
            {
                'name': 'TTS (Text-to-Speech)',
                'description': 'Convert any text or markdown content to high-quality speech audio.',
                'url': 'mini-apps-tts',
                'thumbnail': 'https://images.unsplash.com/photo-1589254065878-42c9da997008?w=400&h=300&fit=crop',
                'icon': 'fas fa-volume-up',
                'color': '#8e44ad'
            },
            {
                'name': 'FIRE Planning',
                'description': 'Plan your Financial Independence Retire Early (FIRE) journey with interactive calculators, projections, and visualizations.',
                'url': 'mini-apps-fire-planning',
                'thumbnail': 'https://images.unsplash.com/photo-1579621970563-ebec7560ff3e?w=400&h=300&fit=crop',
                'icon': 'fas fa-chart-line',
                'color': '#27ae60'
            },
            {
                'name': 'Weather Dashboard',
                'description': 'Real-time weather information with beautiful visualizations and forecasts.',
                'url': '#',
                'thumbnail': 'https://images.unsplash.com/photo-1504608524841-42fe6f032b4b?w=400&h=300&fit=crop',
                'icon': 'fas fa-cloud-sun',
                'color': '#e74c3c'
            },
        ]

        context['mini_apps'] = mini_apps
        return context


class ImageGalleryView(TemplateView):
    template_name = 'links/mini_apps/image_gallery.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Add any context data needed for the image gallery
        return context


class TTSView(TemplateView):
    template_name = 'links/mini_apps/tts.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_title'] = 'Text-to-Speech'
        return context


class FIREPlanningView(TemplateView):
    template_name = 'links/mini_apps/fire_planning.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_title'] = 'FIRE Planning Calculator'
        return context


# ---------------------------------------------------------------------------
# Nginx IP Ban mini app
# ---------------------------------------------------------------------------

_CONFIGMAP_NAME = 'ingress-nginx-controller'
_CONFIGMAP_NS   = 'ingress-nginx'
_CONFIGMAP_KEY  = 'block-cidrs-manual'


def _k8s_v1():
    """Return a CoreV1Api client, preferring in-cluster then local kubeconfig."""
    from kubernetes import client, config
    try:
        config.load_incluster_config()
    except config.ConfigException:
        config.load_kube_config()
    return client.CoreV1Api()


def _read_blocked_ips() -> list[str]:
    v1 = _k8s_v1()
    cm = v1.read_namespaced_config_map(_CONFIGMAP_NAME, _CONFIGMAP_NS)
    raw = (cm.data or {}).get(_CONFIGMAP_KEY, '')
    return [ip.strip() for ip in raw.split(',') if ip.strip()]


def _write_blocked_ips(ips: list[str]) -> None:
    v1 = _k8s_v1()
    from kubernetes.client import V1ConfigMap
    body = V1ConfigMap(data={_CONFIGMAP_KEY: ','.join(ips)})
    v1.patch_namespaced_config_map(_CONFIGMAP_NAME, _CONFIGMAP_NS, body)


class NginxIPBanView(View):
    template = 'links/mini_apps/ip_ban.html'

    def get(self, request):
        error = None
        blocked = []
        try:
            blocked = _read_blocked_ips()
        except Exception as exc:
            logger.error('ip_ban: failed to read ConfigMap: %s', exc)
            error = str(exc)
        return render(request, self.template, {'blocked': blocked, 'error': error})

    def post(self, request):
        action = request.POST.get('action')
        try:
            blocked = _read_blocked_ips()
            if action == 'add':
                raw = request.POST.get('ips', '')
                # Accept comma- or newline-separated entries
                new_ips = [
                    ip.strip()
                    for part in raw.replace('\n', ',').split(',')
                    for ip in [part.strip()]
                    if ip
                ]
                added = 0
                for ip in new_ips:
                    if ip not in blocked:
                        blocked.append(ip)
                        added += 1
                _write_blocked_ips(blocked)
                return JsonResponse({'ok': True, 'blocked': blocked, 'added': added})

            elif action == 'remove':
                ip = request.POST.get('ip', '').strip()
                if ip in blocked:
                    blocked.remove(ip)
                    _write_blocked_ips(blocked)
                return JsonResponse({'ok': True, 'blocked': blocked})

            return JsonResponse({'ok': False, 'error': 'Unknown action'}, status=400)

        except Exception as exc:
            logger.error('ip_ban: action=%s error=%s', action, exc)
            return JsonResponse({'ok': False, 'error': str(exc)}, status=500)
