# (c) cavaliba.com - data/api - aaa.py

"""
API key authentication for app_data.api views: reads the X-Cavaliba-Key header,
validates it against a "_apikey" Instance, resolves its ACL (permission keynames
and role: entries) into aaa["perms"], and optionally gates on a required
permission. Also tracks per-key success/error counters.

The header value is "<keyname> <secret>" for a plain apikey call, or
"<keyname> <secret> <identity>" when the caller also needs to identify itself
as a specific downstream entity (e.g. a CMT agent identifying which _cmtagent
it is) - the optional 3rd token is exposed as aaa["identity"] ("" if absent).
Every existing 2-token caller is unaffected.

Method inventory:
    api_deny_reason, api_update_error, api_update_success, check_ip_filter, start_api
"""

import re

from django.db.models import F
from django.utils import timezone

import app_home.cache as cache
from app_data import crypto
from app_data.data import Instance
from app_data.ip import get_user_ip
from app_data.role import Role
from app_data.telemetry import request_id, telemetry, telemetry_flush
from app_home.log import log2
from app_home.models import CavalibaAPIStat


def api_update_error(keyname=None):
    """Increment error_count and set last_error=now for this API key's stat row."""
    if not keyname:
        return
    CavalibaAPIStat.objects.get_or_create(keyname=keyname)
    CavalibaAPIStat.objects.filter(keyname=keyname).update(
        error_count=F("error_count") + 1, last_error=timezone.now()
    )


def api_update_success(keyname=None):
    """Increment success_count and set last_success=now for this API key's stat row."""
    if not keyname:
        return
    CavalibaAPIStat.objects.get_or_create(keyname=keyname)
    CavalibaAPIStat.objects.filter(keyname=keyname).update(
        success_count=F("success_count") + 1, last_success=timezone.now()
    )


def check_ip_filter(ip, filter):
    """Return True; placeholder for future ACL-based IP filtering (TODO)."""
    # TODO : ip in ACL filter ?
    return True


# start_api() error message -> log2 reason slug
_DENY_REASONS = {
    "missing key": "missing_key",
    "invalid credentials": "invalid_credentials",
    "unauthoried credentials": "ip_denied",
    "invalid permission": "permission_denied",
}


def api_deny_reason(aaa):
    """Return the log2 reason slug for a denied start_api() aaa dict."""

    return _DENY_REASONS.get((aaa or {}).get("error", ""), "denied")


def start_api(request, permission=None):
    """Authenticate the request's API key (X-Cavaliba-Key header), resolve its ACL
    into aaa["perms"], and check the optional required `permission`. Returns an aaa
    dict with is_allowed=True/False and an error message; never raises.
    A refusal is logged here (log2.deny), once per request."""

    aaa = _start_api(request, permission=permission)
    match = getattr(request, "resolver_match", None)
    endpoint = match.url_name.removeprefix("api_") if match else ""
    telemetry("api.request", id=endpoint)
    telemetry_flush()  # safety net, see start_view
    request_id(f"api.{endpoint}" if endpoint else "api")
    if not aaa["is_allowed"]:
        log2.deny("api.access", reason=api_deny_reason(aaa),
                  extra={"permission": permission} if permission else None)  # fmt: skip
    return aaa


def _start_api(request, permission=None):
    """start_api() body: build and return the aaa dict, without logging the outcome."""

    aaa = {}
    aaa["keyname"] = None
    aaa["identity"] = ""
    aaa["is_readonly"] = True
    aaa["error"] = "no action performed"
    aaa["acl"] = None

    aaa["is_trusted_ip"] = False
    aaa["is_anonymous"] = True
    aaa["is_authenticated"] = False
    aaa["is_visitor"] = False
    aaa["is_admin"] = False
    aaa["is_allowed"] = False
    aaa["user"] = None
    aaa["userid"] = None
    aaa["username"] = "API:?"
    aaa["user_ip"] = get_user_ip(request)

    aaa["perms"] = []

    cache.init()
    log2.enter(channel="api", origin=request.path, actor_kind="apikey", client_ip=aaa["user_ip"])

    cavaliba_auth = request.headers.get("X-Cavaliba-Key", "")
    if not cavaliba_auth:
        aaa["error"] = "missing key"
        return aaa

    parts = cavaliba_auth.split(None, 2)
    if len(parts) < 2:
        aaa["error"] = "invalid credentials"
        return aaa
    keyname, clear_secret = parts[0], parts[1]
    aaa["identity"] = parts[2] if len(parts) > 2 else ""

    m = re.compile(r"[a-zA-Z0-9()_/.-]*$")

    if not keyname:
        aaa["error"] = "invalid credentials"
        return aaa
    if not m.match(keyname):
        aaa["error"] = "invalid credentials"
        return aaa

    aaa["keyname"] = keyname
    log2.bind(actor="API:" + keyname)

    instance = Instance.from_keyname(classname="_apikey", keyname=keyname)
    if not instance:
        aaa["error"] = "invalid credentials"
        return aaa

    if not instance.is_enabled:
        aaa["error"] = "invalid credentials"
        api_update_error(keyname)
        return aaa

    instance.fields["is_readonly"].get_first_value()

    if not crypto.hash_check(clear_secret, instance.fields["secret"].get_first_value()):
        aaa["error"] = "invalid credentials"
        api_update_error(keyname)
        return aaa

    aaa["is_authenticated"] = True
    aaa["is_readonly"] = instance.fields["is_readonly"].get_first_value()

    user_ip = get_user_ip(request)
    aaa["user_ip"] = user_ip
    ip_filter = instance.fields["ip_filter"].get_first_value()

    if len(ip_filter) > 0:
        r = check_ip_filter(user_ip, ip_filter)
        if not r:
            aaa["error"] = "unauthoried credentials"
            api_update_error(keyname)
            return aaa

    try:
        aaa["acl"] = instance.fields["acl"].get_first_value()
    except Exception:
        aaa["acl"] = ""

    aaa["perms"] = []
    perms = []

    try:
        acl_entries = instance.fields["acl"].get_first_value().splitlines()
    except Exception:
        acl_entries = []

    for acl in acl_entries:
        if acl.startswith("!"):
            negate = True
            acl2 = acl[1:]
        else:
            negate = False
            acl2 = acl

        if ":" in acl2:
            if acl2.startswith("role:"):
                rolename = acl2[5:]
                role = Role.from_keyname(keyname=rolename)

                roleperms = []
                if role and role.is_bound:
                    roleperms = [p.keyname for p in role.get_permissions()]

                for p in roleperms:
                    if negate:
                        if p in perms:
                            perms.remove(p)
                    else:
                        if p not in perms:
                            perms.append(p)
        else:
            if len(acl2) > 0:
                if negate:
                    if acl2 in perms:
                        perms.remove(acl2)
                else:
                    if acl2 not in perms:
                        perms.append(acl2)

    aaa["perms"] = list(set(perms))

    if permission:
        if permission not in aaa["perms"]:
            aaa["error"] = "invalid permission"
            api_update_error(keyname)
            return aaa

    api_update_success(keyname)
    aaa["is_allowed"] = True
    aaa["error"] = ""
    aaa["username"] = "API:" + aaa["keyname"]

    sync_param = request.GET.get("sync", "")
    aaa["sync_mode"] = sync_param.lower() in ("1", "true", "yes")

    return aaa
