# (c) cavaliba.com - data/api - task.py
#
# GET  /api/tasks/                  list tasks (own or all for admin)
# GET  /api/tasks/<handle>/         poll progress
# POST /api/tasks/<handle>/stop/    abort task

"""
Async DataTask lifecycle over the API: list (own tasks, or all for
p_data_admin), poll a single task's progress, and stop (abort) one.

All three endpoints are gated on p_data_access alone. Stopping a task the
calling key owns needs nothing more (5.4.0 - it used to require
p_task_manage); stopping another owner's needs p_data_admin to see it at all,
plus p_task_manage to act on it. Same shape as the UI, see
app_data/views_task.py - except that the UI's widening permission is
p_task_all, which has no effect here.

"Owns" means dt.owner_id is the calling key's keyname (see _owns): a task
submitted through /api/ is owned by the key that submitted it. Tasks created
by a user in the UI are owned by that login, and CLI ones by "system", so
neither is ever a key's own task - they need p_data_admin + p_task_manage.

Method inventory: _task_to_dict, _is_admin, _owns, _stop_refusal, task_list,
task_detail, task_stop.
"""

from django.views.decorators.csrf import csrf_exempt

import app_data.api.helper as helper
from app_data.api.aaa import start_api
from app_data.datetimeutil import iso_seconds
from app_data.models import DataTask
from app_data.task_manager import abort_task
from app_home.log import WARNING, log2


def _task_to_dict(dt):
    """Return the exportable dict for a DataTask row (handle, state, progress, ...)."""
    return {
        "handle": str(dt.handle),
        "name": dt.name,
        "state": dt.state,
        "owner_type": dt.owner_type,
        "owner_id": dt.owner_id,
        "singleton": dt.singleton,
        "params": dt.params,
        "progress": dt.progress,
        "output": dt.output,
        "attachment": dt.attachment,
        "created_at": iso_seconds(dt.created_at) if dt.created_at else None,
        "finished_at": iso_seconds(dt.finished_at) if dt.finished_at else None,
        "duration": dt.duration,
    }


def _is_admin(aaa_api):
    """Return True if the authenticated API key/user has p_data_admin."""
    return "p_data_admin" in aaa_api.get("perms", [])


def _owns(aaa_api, dt):
    """Return True if the authenticated API key/user is the owner of DataTask dt."""
    return aaa_api.get("keyname") == dt.owner_id or aaa_api.get("username") == dt.owner_id


def _stop_refusal(aaa_api, dt):
    """Why this caller may not stop `dt`, as a (reason, message) pair, or None.

    A task the key owns needs no permission beyond the endpoint's own
    p_data_access - the same rule as the UI's Stop button and as the Abort button
    of the import/export progress modal. Another owner's task needs p_data_admin
    (without it the task is not even visible here) plus p_task_manage.
    """

    if _owns(aaa_api, dt):
        return None
    if not _is_admin(aaa_api):
        return "not_owner", "not your task"
    if "p_task_manage" not in aaa_api.get("perms", []):
        return "permission_denied", "p_task_manage permission required"
    return None


# ------------------------------------------------------------------
# GET /api/tasks/
# ------------------------------------------------------------------


@csrf_exempt
def task_list(request):
    """GET-only: paginated list of DataTask, restricted to the caller's own tasks
    unless p_data_admin; optional ?state= filter."""

    aaa_api = start_api(request, permission="p_data_access")
    if not aaa_api["is_allowed"]:
        return helper.send_denied(aaa_api["error"])

    if request.method != "GET":
        log2.fail("task.list", reason="method_not_allowed")
        return helper.send_error("method not allowed", 405)

    page = helper.get_page(request)
    size = helper.get_size(request)
    state_filter = request.GET.get("state", "").strip()

    qs = DataTask.objects.all()

    if not _is_admin(aaa_api):
        owner_id = aaa_api.get("keyname") or aaa_api.get("username") or ""
        qs = qs.filter(owner_id=owner_id)

    if state_filter:
        qs = qs.filter(state=state_filter.upper())

    total = qs.count()
    offset = (page - 1) * size
    tasks = qs[offset : offset + size]

    reply = {
        "total": total,
        "page": page,
        "size": size,
        "tasks": [_task_to_dict(dt) for dt in tasks],
    }

    log2.access("task.list", count=total)

    return helper.send_response(request, reply, 200)


# ------------------------------------------------------------------
# GET /api/tasks/<handle>/
# ------------------------------------------------------------------


@csrf_exempt
def task_detail(request, handle):
    """GET-only: return one DataTask's full dict if the caller owns it or is admin."""

    aaa_api = start_api(request, permission="p_data_access")
    if not aaa_api["is_allowed"]:
        return helper.send_denied(aaa_api["error"])

    if request.method != "GET":
        log2.fail("task.detail", reason="method_not_allowed")
        return helper.send_error("method not allowed", 405)

    try:
        dt = DataTask.objects.get(handle=handle)
    except (DataTask.DoesNotExist, Exception):
        log2.fail("task.detail", reason="not_found", target=("task", handle))
        return helper.send_not_found("task not found")

    if not (_owns(aaa_api, dt) or _is_admin(aaa_api)):
        log2.deny("task.detail", reason="not_owner", target=("task", handle))
        return helper.send_denied("not your task")

    log2.access("task.detail", target=("task", handle))

    return helper.send_response(request, _task_to_dict(dt), 200)


# ------------------------------------------------------------------
# POST /api/tasks/<handle>/stop/
# ------------------------------------------------------------------


@csrf_exempt
def task_stop(request, handle):
    """POST-only: abort a DataTask (via abort_task). The calling key's own task
    needs no permission beyond p_data_access; another owner's needs p_data_admin
    plus p_task_manage (see _stop_refusal)."""

    aaa_api = start_api(request, permission="p_data_access")
    if not aaa_api["is_allowed"]:
        return helper.send_denied(aaa_api["error"])

    if request.method != "POST":
        log2.fail("task.stop", reason="method_not_allowed")
        return helper.send_error("method not allowed", 405)

    if aaa_api.get("is_readonly"):
        log2.deny("task.stop", reason="readonly_key")
        return helper.send_denied("API key is read-only")

    try:
        dt = DataTask.objects.get(handle=handle)
    except (DataTask.DoesNotExist, Exception):
        log2.fail("task.stop", reason="not_found", target=("task", handle))
        return helper.send_not_found("task not found")

    refusal = _stop_refusal(aaa_api, dt)
    if refusal:
        reason, message = refusal
        log2.deny("task.stop", reason=reason, target=("task", handle))
        return helper.send_denied(message)

    ok = abort_task(dt.handle, aaa=aaa_api)

    if ok:
        log2.ok("task.stop", target=("task", handle))
    else:
        log2.fail("task.stop", reason="not_running", target=("task", handle), level=WARNING)

    reply = {"handle": str(handle), "aborted": ok}
    return helper.send_response(request, reply, 200)
