# ============================================================
# Case Documents - confidential investigation vault          /api/relations/documents/
# Restricted to Company Admin, HR Head, Legal Counsel and named vault members (Settings).  Every action is logged.
# Files are stored OUTSIDE MEDIA_ROOT (private_media/) and can only be fetched through the audited download endpoint.
# ============================================================
import hashlib
import os

from django.http import FileResponse
from rest_framework.decorators import action
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser

from .common import (CaseDocument, DisciplinaryAction, DocumentAccessLog, IsVaultUser, LegalCase, RelCrud, actor_label, add_note, central_audit, err, get_client_ip,
                     doc_row, ok, paginate, to_int, who)
from .views_discipline import find_case

MAX_BYTES = 10 * 1024 * 1024
ALLOWED = {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".png", ".jpg", ".jpeg", ".txt", ".eml", ".msg"}


def log_access(request, doc, act):
    DocumentAccessLog.objects.create(company=doc.company, document=doc, action=act, actor=actor_label(request.user), actor_name=who(request.user),
                                     ip_address=get_client_ip(request))


def log_row(l):
    return {"id": l.id, "document_id": l.document_id, "document": l.document.title, "action": l.action, "actor": l.actor_name, "ip_address": l.ip_address,
            "at": l.created_at.isoformat()}


class DocumentViewSet(RelCrud):
    """
    CRUD   /api/relations/documents/                ?case=<id|CASE-01> ?legal_case=<id|LEG-2026-01> ?disciplinary=<id> ?doc_type= ?confidentiality= ?search=
    POST   multipart/form-data: file, title?, doc_type?, description?, confidentiality?(Confidential|Restricted), and ONE OF case / disciplinary_id / legal_case
    PATCH  /<id>/       metadata (title, doc_type, description, confidentiality) and optionally a replacement `file`
    GET    /<id>/download/        the file (logged)          GET /<id>/access-log/     GET /access-log/    full audit trail
    DELETE /<id>/         soft delete (the file is kept for legal hold)
    Types accepted: pdf, doc, docx, xls, xlsx, png, jpg, jpeg, txt, eml, msg - max 10 MB.  A file with the same SHA-256 on the same matter is rejected.
    """
    model, code, module_label = CaseDocument, "CASE_DOCUMENT", "Case Documents"
    permission_classes = [IsVaultUser]
    parser_classes = [MultiPartParser, FormParser, JSONParser]
    select = ("case", "legal_case", "disciplinary")
    search_fields = ("title", "file_name", "description", "case__case_no", "legal_case__legal_no")
    status_field = None
    ref_field = "title"
    permission_action_map = {"download": "view", "access_log": "view", "all_access_log": "view"}

    def build(self, d):
        return doc_row(d, self.request)

    def filter(self, qs, p):
        qs = super().filter(qs, {k: v for k, v in p.items() if k != "employee"})
        if p.get("case"):
            qs = qs.filter(case_id=int(p["case"])) if str(p["case"]).isdigit() else qs.filter(case__case_no__iexact=p["case"])
        if p.get("legal_case"):
            qs = qs.filter(legal_case_id=int(p["legal_case"])) if str(p["legal_case"]).isdigit() else qs.filter(legal_case__legal_no__iexact=p["legal_case"])
        if p.get("disciplinary"):
            qs = qs.filter(disciplinary_id=int(p["disciplinary"]))
        if p.get("doc_type"):
            qs = qs.filter(doc_type__iexact=p["doc_type"])
        if p.get("confidentiality"):
            qs = qs.filter(confidentiality__iexact=p["confidentiality"])
        return qs

    def retrieve(self, request, pk=None):
        d = self.scope().filter(pk=pk, is_active=True).first()
        if d is None:
            return err("NOT_FOUND", "Record not found.", 404)
        log_access(request, d, "VIEW")
        return ok("CASE_DOCUMENT_DETAIL", "Detail fetched.", doc_row(d, request))

    def _file(self, d, f):
        if f is None:
            return None
        ext = os.path.splitext(f.name)[1].lower()
        if ext not in ALLOWED:
            raise ValueError(f"File type '{ext or 'unknown'}' is not allowed. Allowed: {', '.join(sorted(ALLOWED))}.")
        if f.size <= 0:
            raise ValueError("The file is empty.")
        if f.size > MAX_BYTES:
            raise ValueError("The file is larger than 10 MB.")
        h = hashlib.sha256()
        for chunk in f.chunks():
            h.update(chunk)
        f.seek(0)
        return h.hexdigest()

    def apply(self, d, data, creating):
        co, req = self.company(), self.request
        f = req.FILES.get("file")
        if creating:
            if f is None:
                raise ValueError("file is required (multipart/form-data).")
            if data.get("case"):
                d.case = find_case(co, data["case"])
            if data.get("disciplinary_id"):
                d.disciplinary = DisciplinaryAction.objects.filter(company=co, is_active=True, pk=to_int(data["disciplinary_id"])).first()
                if d.disciplinary is None:
                    raise ValueError("disciplinary_id not found.")
            if data.get("legal_case"):
                q = LegalCase.objects.filter(company=co, is_active=True)
                ref = data["legal_case"]
                d.legal_case = q.filter(pk=int(ref)).first() if str(ref).isdigit() else q.filter(legal_no__iexact=str(ref)).first()
                if d.legal_case is None:
                    raise ValueError(f"Legal case '{ref}' not found.")
            if not (d.case_id or d.disciplinary_id or d.legal_case_id):
                raise ValueError("Attach the document to a matter: case, disciplinary_id or legal_case.")
        t = next((x for x in CaseDocument.TYPES if x.lower() == str(data.get("doc_type") or d.doc_type or "").lower()), None)
        if t is None:
            raise ValueError(f"doc_type must be one of: {', '.join(CaseDocument.TYPES)}.")
        d.doc_type = t
        cl = next((x for x in CaseDocument.LEVELS if x.lower() == str(data.get("confidentiality") or d.confidentiality or "").lower()), None)
        if cl is None:
            raise ValueError(f"confidentiality must be one of: {', '.join(CaseDocument.LEVELS)}.")
        d.confidentiality = cl
        title = (data.get("title") or d.title or (f.name if f else "")).strip()
        if not title:
            raise ValueError("title is required.")
        d.title = title[:250]
        if "description" in data:
            d.description = data["description"]
        sha = self._file(d, f)
        if sha:
            q = CaseDocument.objects.filter(sha256=sha, case=d.case, disciplinary=d.disciplinary, legal_case=d.legal_case)
            if d.pk:
                q = q.exclude(pk=d.pk)
            self.dup(q, "Duplicate: this exact file is already in the vault for the same matter.")
            d._old_path = d.file.name if d.pk and d.file else None
            d.file.save(f.name, f, save=False)
            d.file_name, d.file_size, d.content_type, d.sha256 = f.name[:255], f.size, getattr(f, "content_type", None), sha
            if creating:
                d.uploaded_by = self.actor()

    def after_save(self, d, creating):
        log_access(self.request, d, "UPLOAD" if creating else "UPDATE")
        if creating and d.case_id:
            add_note(d.case, self.request.user, f"Document added to the vault: {d.title}.", "Document", True)
        old = getattr(d, "_old_path", None)
        if old and old != d.file.name:
            try:
                d.file.storage.delete(old)
            except Exception:
                pass

    def after_delete(self, d):
        log_access(self.request, d, "DELETE")

    def _doc(self, pk):
        return self.scope().filter(pk=pk, is_active=True).first()

    @action(detail=True, methods=["get"], url_path="download")
    def download(self, request, pk=None):
        d = self._doc(pk)
        if d is None or not d.file or not d.file.storage.exists(d.file.name):
            return err("NOT_FOUND", "Document not found.", 404)
        log_access(request, d, "DOWNLOAD")
        central_audit(request, self.company(), "DOWNLOAD", self.module_label, d.title)
        return FileResponse(d.file.open("rb"), as_attachment=True, filename=d.file_name, content_type=d.content_type or "application/octet-stream")

    @action(detail=True, methods=["get"], url_path="access-log")
    def access_log(self, request, pk=None):
        d = self._doc(pk)
        if d is None:
            return err("NOT_FOUND", "Document not found.", 404)
        rows, meta = paginate(request, d.access_logs.select_related("document"), log_row)
        return ok("DOCUMENT_ACCESS_LOG", "Access log.", rows, meta=meta)

    @action(detail=False, methods=["get"], url_path="access-log")
    def all_access_log(self, request):
        qs = DocumentAccessLog.objects.filter(company=self.company()).select_related("document")
        if request.query_params.get("action"):
            qs = qs.filter(action=request.query_params["action"].upper())
        rows, meta = paginate(request, qs, log_row)
        return ok("DOCUMENT_ACCESS_LOG", "Access log.", rows, meta=meta)
