# ============================================================
# Security Center / System Health / Backup & Data / Audit Trail / Control Center summary
#   /api/admin-center/security/  /system-health/  /backup/  /audit/  /summary/
# ============================================================
import csv
import ipaddress
import json
import os
from datetime import timedelta

from django.conf import settings
from django.db.models import Q
from django.http import FileResponse, HttpResponse
from django.utils import timezone
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet

from Company.models import AuthLog, get_client_ip
from Employee.models import EmployeeAccount, EmployeeDT

from . import services
from .common import (AuditedCrud, CenterAuthMixin, active_sessions, err, iso, log_event, ok, paginate, to_bool, to_date, to_int)
from .models import AdminAuditEvent, BackupPolicy, BackupSnapshot, LegalEntity


# ---------------- Security Center ----------------
POLICY_BOOLS = ("mfa_required_admins", "lockout_enabled", "password_rotation_enabled", "idle_timeout_enabled", "ip_allowlist_enabled")
POLICY_INTS = {"lockout_attempts": (1, 20), "lockout_minutes": (1, 1440), "password_rotation_days": (7, 365), "password_history": (0, 24), "idle_timeout_minutes": (5, 480)}


def policy_row(p):
    return {**{k: getattr(p, k) for k in POLICY_BOOLS}, **{k: getattr(p, k) for k in POLICY_INTS}, "ip_allowlist": p.ip_allowlist,
            "updated_at": iso(p.updated_at)}


class SecurityView(CenterAuthMixin, APIView):
    """
    GET       /api/admin-center/security/        policy + posture KPIs + threat log
    PUT/PATCH /api/admin-center/security/        {mfa_required_admins, lockout_enabled, lockout_attempts, lockout_minutes, password_rotation_enabled,
                                                  password_rotation_days, password_history, idle_timeout_enabled, idle_timeout_minutes,
                                                  ip_allowlist_enabled, ip_allowlist:["203.0.113.5", "10.0.0.0/24"]}
    POST      /api/admin-center/security/scan/              [Run Security Scan]
    POST      /api/admin-center/security/enforce-lockouts/  lock accounts that reached the failed-attempt limit
    """
    def get(self, request):
        co = self.company()
        p = services.get_policy(co)
        return ok("SECURITY_CENTER", "Security center.", {
            "policy": policy_row(p), "security_posture": services.posture_score(p), "mfa_enforced": p.mfa_required_admins,
            "failed_logins_24h": services.failed_logins(co).count(), "locked_accounts": services.locked_accounts(co).count(),
            "threat_detection_logs": services.threats(co)})

    def put(self, request):
        co, d = self.company(), request.data
        p = services.get_policy(co)
        before = policy_row(p)
        try:
            for k in POLICY_BOOLS:
                if k in d:
                    if not isinstance(d[k], bool):
                        raise ValueError(f"{k} must be true or false.")
                    setattr(p, k, d[k])
            for k, (lo, hi) in POLICY_INTS.items():
                if k in d:
                    v = to_int(d[k])
                    if v is None or not lo <= v <= hi:
                        raise ValueError(f"{k} must be between {lo} and {hi}.")
                    setattr(p, k, v)
            if "ip_allowlist" in d:
                lst = d["ip_allowlist"]
                if not isinstance(lst, list):
                    raise ValueError("ip_allowlist must be a list.")
                for x in lst:
                    ipaddress.ip_network(str(x), strict=False)
                p.ip_allowlist = [str(x) for x in lst]
            if p.ip_allowlist_enabled:
                me = get_client_ip(request)
                nets = [ipaddress.ip_network(x, strict=False) for x in p.ip_allowlist]
                if not p.ip_allowlist or (me and not any(ipaddress.ip_address(me) in n for n in nets)):
                    raise ValueError(f"Enabling the allow-list would lock you out (your IP {me} is not in it). Add your IP first.")
        except ValueError as e:
            return err("VALIDATION", str(e))
        p.updated_by = self.actor()
        p.save()
        new = policy_row(p)
        log_event(request, co, "UPDATED", "Security", "security-policy", {k: before[k] for k in new if before[k] != new[k] and k != "updated_at"},
                  {k: new[k] for k in new if before[k] != new[k] and k != "updated_at"})
        return ok("SECURITY_UPDATED", "Security policy updated.", {"policy": new, "security_posture": services.posture_score(p)})

    patch = put


class SecurityScanView(CenterAuthMixin, APIView):
    permission_action = "edit"

    def post(self, request):
        res = services.security_scan(self.company())
        log_event(request, self.company(), "SECURITY_SCAN", "Security", "scan", None, f"score {res['score']}, {len(res['findings'])} finding(s)")
        return ok("SECURITY_SCAN", f"Scan complete: {len(res['findings'])} finding(s).", res)


class EnforceLockoutsView(CenterAuthMixin, APIView):
    permission_action = "edit"

    def post(self, request):
        n = services.lockout_sweep(self.company(), self.actor())
        return ok("LOCKOUTS_ENFORCED", f"{n} account(s) locked.", {"locked": n})


# ---------------- System Health ----------------
class HealthView(CenterAuthMixin, APIView):
    """GET /api/admin-center/system-health/      [Refresh Checks = call again]"""
    permission_action = "view"

    def get(self, request):
        return ok("SYSTEM_HEALTH", "System health.", services.health(self.company()))


# ---------------- Backup & Data ----------------
def snap_row(s):
    return {"id": s.id, "policy_id": s.policy_id, "size_bytes": s.size_bytes, "snapshot_size": services.human_size(s.size_bytes), "checksum_sha256": s.checksum,
            "record_counts": s.record_counts, "status": s.status, "triggered_by": s.triggered_by, "created_at": iso(s.created_at)}


def policy_backup_row(p):
    last = p.snapshots.filter(is_active=True).first()
    return {"id": p.id, "backup_target": p.target, "target": p.target, "frequency": p.frequency, "retention_days": p.retention_days,
            "retention_period": f"{p.retention_days} Days", "storage_location": p.storage_location, "status": p.status,
            "snapshot_size": services.human_size(last.size_bytes) if last else None, "last_snapshot_at": iso(last.created_at) if last else None,
            "last_snapshot_status": last.status if last else None, "created_at": iso(p.created_at)}


class BackupPolicyViewSet(AuditedCrud):
    """
    CRUD   /api/admin-center/backup/policies/       {target, frequency, retention_days?, storage_location?, status?: Active|Paused}
    POST   /api/admin-center/backup/policies/<id>/trigger/     run this policy now
    """
    model, code, module_label = BackupPolicy, "BACKUP_POLICY", "Backup & Data"
    ref_field = "target"
    search_fields = ("target", "frequency", "storage_location")
    unique_fields = ("target",)
    permission_action_map = {"trigger": "edit"}

    def build(self, p):
        return policy_backup_row(p)

    def apply(self, p, d, creating):
        t = (d.get("target") or p.target or "").strip()
        f = (d.get("frequency") or p.frequency or "").strip()
        if not t or not f:
            raise ValueError("target and frequency are required.")
        p.target, p.frequency = t, f
        self.dup(p, target=t)
        if "retention_days" in d:
            r = to_int(d["retention_days"])
            if r is None or not 1 <= r <= 3650:
                raise ValueError("retention_days must be between 1 and 3650.")
            p.retention_days = r
        if "storage_location" in d:
            p.storage_location = d["storage_location"]
        if "status" in d:
            if d["status"] not in ("Active", "Paused"):
                raise ValueError("status must be Active or Paused.")
            p.status = d["status"]

    @action(detail=True, methods=["post"], url_path="trigger")
    def trigger(self, request, pk=None):
        p = self.scope().filter(pk=pk, is_active=True).first()
        if p is None:
            return err("NOT_FOUND", "Record not found.", 404)
        s = services.create_snapshot(self.company(), self.actor(), p)
        log_event(request, self.company(), "BACKUP", "Backup & Data", p.target, None, f"snapshot #{s.id}")
        return ok("BACKUP_TRIGGERED", "Backup completed.", snap_row(s), 201)


class SnapshotViewSet(CenterAuthMixin, ViewSet):
    """
    GET    /api/admin-center/backup/snapshots/            list         GET /<id>/  detail
    GET    /api/admin-center/backup/snapshots/<id>/download/            the JSON file
    DELETE /api/admin-center/backup/snapshots/<id>/      remove snapshot + file
    POST   /api/admin-center/backup/trigger/             [Trigger Backup Now]   (also POST .../backup/snapshots/)
    GET    /api/admin-center/backup/export/              [Export Full JSON]  config export, never passwords / secrets
    """
    permission_action_map = {"download": "view", "export": "view", "trigger": "edit"}

    def _qs(self):
        return BackupSnapshot.objects.filter(company=self.company(), is_active=True)

    def list(self, request):
        rows, meta = paginate(request, self._qs(), snap_row)
        return ok("SNAPSHOT_LIST", "Snapshots.", rows, meta=meta)

    def retrieve(self, request, pk=None):
        s = self._qs().filter(pk=pk).first()
        return ok("SNAPSHOT_DETAIL", "Snapshot.", snap_row(s)) if s else err("NOT_FOUND", "Record not found.", 404)

    def create(self, request):
        return self.trigger(request)

    @action(detail=False, methods=["post"], url_path="trigger")
    def trigger(self, request):
        s = services.create_snapshot(self.company(), self.actor())
        log_event(request, self.company(), "BACKUP", "Backup & Data", f"snapshot #{s.id}", None, f"{s.size_bytes} bytes")
        return ok("BACKUP_TRIGGERED", "Backup completed.", snap_row(s), 201)

    def destroy(self, request, pk=None):
        s = self._qs().filter(pk=pk).first()
        if s is None:
            return err("NOT_FOUND", "Record not found.", 404)
        services.drop_snapshot(s)
        log_event(request, self.company(), "DELETED", "Backup & Data", f"snapshot #{pk}")
        return ok("SNAPSHOT_DELETED", "Snapshot deleted.", {"id": int(pk)})

    @action(detail=True, methods=["get"], url_path="download")
    def download(self, request, pk=None):
        s = self._qs().filter(pk=pk).first()
        root = os.path.abspath(settings.MEDIA_ROOT)
        if s is None or not s.file_path or not os.path.abspath(s.file_path).startswith(root) or not os.path.exists(s.file_path):
            return err("NOT_FOUND", "Snapshot file not found.", 404)
        return FileResponse(open(s.file_path, "rb"), as_attachment=True, filename=os.path.basename(s.file_path), content_type="application/json")

    @action(detail=False, methods=["get"], url_path="export")
    def export(self, request):
        data = services.build_export(self.company())
        log_event(request, self.company(), "EXPORT", "Backup & Data", "full-json")
        r = HttpResponse(json.dumps(data, indent=2, default=str, ensure_ascii=False), content_type="application/json")
        r["Content-Disposition"] = 'attachment; filename="admin_center_export.json"'
        return r


# ---------------- Audit Trail (append-only) ----------------
def audit_row(a):
    return {"id": a.id, "timestamp": iso(a.created_at), "user_actor": a.actor_name, "actor": a.actor, "action": a.action, "module": a.module,
            "record_reference": a.record_ref, "old_value": a.old_value, "new_value": a.new_value, "ip_source": a.ip_address}


def audit_filter(qs, p):
    if p.get("module"):
        qs = qs.filter(module__iexact=p["module"])
    if p.get("action"):
        qs = qs.filter(action__iexact=p["action"])
    if p.get("actor"):
        qs = qs.filter(Q(actor__icontains=p["actor"]) | Q(actor_name__icontains=p["actor"]))
    if p.get("record_ref"):
        qs = qs.filter(record_ref__icontains=p["record_ref"])
    if p.get("search"):
        qs = qs.filter(Q(record_ref__icontains=p["search"]) | Q(old_value__icontains=p["search"]) | Q(new_value__icontains=p["search"]) | Q(module__icontains=p["search"]))
    if p.get("date_from"):
        qs = qs.filter(created_at__date__gte=to_date(p["date_from"]))
    if p.get("date_to"):
        qs = qs.filter(created_at__date__lte=to_date(p["date_to"]))
    return qs


class AuditViewSet(CenterAuthMixin, ViewSet):
    """
    GET   /api/admin-center/audit/         ?module= ?action= ?actor= ?record_ref= ?search= ?date_from= ?date_to= ?page=
    GET   /api/admin-center/audit/<id>/
    POST  /api/admin-center/audit/         {action, module, record_ref?, old_value?, new_value?}   other modules / clients can write events
    GET   /api/admin-center/audit/export/  [Export Audit CSV]
    Update and delete do not exist: the trail is immutable (PUT / PATCH / DELETE -> 405).
    """
    permission_action_map = {"export": "view"}

    def _qs(self):
        return AdminAuditEvent.objects.filter(company=self.company())

    def list(self, request):
        try:
            qs = audit_filter(self._qs(), request.query_params)
        except ValueError as e:
            return err("VALIDATION", str(e))
        rows, meta = paginate(request, qs, audit_row)
        return ok("AUDIT_LIST", "Audit trail.", rows, meta=meta)

    def retrieve(self, request, pk=None):
        a = self._qs().filter(pk=pk).first()
        return ok("AUDIT_DETAIL", "Audit event.", audit_row(a)) if a else err("NOT_FOUND", "Record not found.", 404)

    def create(self, request):
        d = request.data
        act, mod = (d.get("action") or "").strip().upper(), (d.get("module") or "").strip()
        if not act or not mod:
            return err("VALIDATION", "action and module are required.")
        a = log_event(request, self.company(), act[:30], mod[:60], d.get("record_ref"), d.get("old_value"), d.get("new_value"))
        return ok("AUDIT_CREATED", "Event recorded.", audit_row(a), 201) if a else err("ERROR", "Could not record event.", 500)

    @action(detail=False, methods=["get"], url_path="export")
    def export(self, request):
        try:
            qs = audit_filter(self._qs(), request.query_params).order_by("created_at")
        except ValueError as e:
            return err("VALIDATION", str(e))
        r = HttpResponse(content_type="text/csv")
        r["Content-Disposition"] = 'attachment; filename="audit_trail.csv"'
        w = csv.writer(r)
        w.writerow(["Timestamp", "User / Actor", "Action", "Module", "Record Reference", "Old Value", "New Value", "IP Source"])
        for a in qs:
            w.writerow([a.created_at.strftime("%Y-%m-%d %H:%M:%S"), a.actor_name, a.action, a.module, a.record_ref, a.old_value, a.new_value, a.ip_address])
        return r


# ---------------- Control Center summary ----------------
class SummaryView(CenterAuthMixin, APIView):
    """GET /api/admin-center/summary/    KPI cards + 7-day activity + live checks + shortcuts"""
    permission_action = "view"
    sensitive = False

    def get(self, request):
        co, now = self.company(), timezone.now()
        users = EmployeeDT.objects.filter(company=co, is_active=True)
        total = users.count()
        mstart = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        new = users.filter(created_at__gte=mstart).count() if hasattr(EmployeeDT, "created_at") else 0
        base = total - new
        growth = round(new * 100 / base, 1) if base > 0 else None
        today = timezone.localdate()
        days = [today - timedelta(days=i) for i in range(6, -1, -1)]
        act = []
        for d in days:
            n = (AuthLog.objects.filter(company=co, created_at__date=d).count() + AdminAuditEvent.objects.filter(company=co, created_at__date=d).count())
            act.append({"date": d.isoformat(), "day": d.strftime("%a"), "requests_and_operations": n})
        h = services.health(co)
        p = services.get_policy(co)
        return ok("CONTROL_CENTER", "Enterprise admin control center.", {
            "total_users": total + 1, "users_added_this_month": new, "users_growth_percent": growth,
            "active_sessions": len(active_sessions(co)), "operating_companies": LegalEntity.objects.filter(company=co, is_active=True, status="Active").count(),
            "audit_events": AdminAuditEvent.objects.filter(company=co).count(), "security_score": services.posture_score(p),
            "system_activity_last_7_days": act,
            "live_system_checks": {"overall": h["overall"], "probes": [{"name": x["name"], "status": x["status"]} for x in h["probes"]],
                                   "storage_used_percent": h["resources"]["storage_used_percent"]},
            "quick_shortcuts": [{"label": "Users", "path": "/api/admin-center/users/"}, {"label": "Permissions", "path": "/api/admin-center/rbac/matrix/"},
                                {"label": "Workflows", "path": "/api/admin-center/workflows/"}, {"label": "Backup", "path": "/api/admin-center/backup/snapshots/"},
                                {"label": "Integrations", "path": "/api/admin-center/integrations/"}, {"label": "Audit Trail", "path": "/api/admin-center/audit/"}]})
