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

"""
/api/pipelines/: list pipelines, and run one asynchronously (submits a
DataTask via submit_pipeline and returns its polling URL).

Method inventory: _pipeline_to_dict, pipeline_list, pipeline.
"""

from django.urls import reverse
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.pipeline import Pipeline
from app_data.tasks import submit_pipeline
from app_home.log import log2


def _pipeline_to_dict(p):
    """Return the minimal exportable dict for a Pipeline (id, keyname, run_permission)."""
    return {
        "id": p.id,
        "keyname": p.keyname,
        "run_permission": p.run_permission,
    }


#  ----------------------------------------------------------------------------
# GET /api/pipelines/
#  ----------------------------------------------------------------------------
@csrf_exempt
def pipeline_list(request):
    """GET-only: return all pipelines as a list of {id, keyname, run_permission}."""

    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("pipeline.list", reason="method_not_allowed")
        return helper.send_error("method not allowed", 405)

    instances = Pipeline.list()
    pipelines = [_pipeline_to_dict(Pipeline.from_instance(i)) for i in instances]

    log2.access("pipeline.list", count=len(pipelines))

    reply = {
        "count": len(pipelines),
        "pipelines": pipelines,
    }
    return helper.send_response(request, reply, 200)


# permission: p_pipeline_run


#  ----------------------------------------------------------------------------
# POST /api/pipelines/<name>/
# POST /api/pipelines/<id>/
# ?schema=SCHEMANAME,user,...   (comma-separated, required)
# &dryrun=false                 (optional, default: false)
#  ----------------------------------------------------------------------------
@csrf_exempt
def pipeline(request, id=None, key=None):
    """POST-only: resolve the pipeline by id/key, then submit it as an async
    DataTask (via submit_pipeline) over the given comma-separated schema names;
    returns 202 with the task's polling URL."""

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

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

    if aaa_api["is_readonly"]:
        log2.deny("pipeline.run", reason="readonly_key")
        return helper.send_denied("API key is read-only")

    schema_param = request.GET.get("schema", "").strip()
    dryrun_param = request.GET.get("dryrun", "false").strip().lower()
    dryrun = dryrun_param in ("true", "1", "yes")

    if not schema_param:
        log2.fail("pipeline.run", reason="missing_param", extra={"param": "schema"})
        return helper.send_error("missing required parameter: schema", 400)

    schema_names = [s.strip() for s in schema_param.split(",") if s.strip()]
    if not schema_names:
        log2.fail("pipeline.run", reason="missing_param", extra={"param": "schema"})
        return helper.send_error("missing required parameter: schema", 400)

    if id is not None:
        p = Pipeline.from_id(id)
    elif key:
        p = Pipeline.from_name(key)
    else:
        log2.fail("pipeline.run", reason="missing_param", extra={"param": "pipeline"})
        return helper.send_error("missing pipeline identifier", 400)

    if not p:
        log2.fail("pipeline.run", reason="not_found", target=("pipeline", key or id))
        return helper.send_not_found("pipeline not found")

    # the task belongs to the key that submitted it, which is what lets that same
    # key poll and stop it through /api/tasks/ without p_data_admin (see
    # api/task.py). start_api() never binds a user to an API key, so the former
    # aaa_api["user"].id branch always fell back to "system" - leaving every
    # API-submitted task owned by nobody.
    owner_id = aaa_api.get("keyname") or "system"

    # call async task (submit) , immediate return
    handle, err = submit_pipeline(
        pipeline_name=p.keyname,
        schema_names=schema_names,
        dryrun=dryrun,
        aaa=aaa_api,
        owner_type="api",
        owner_id=owner_id,
    )
    if not handle:
        log2.fail("pipeline.run", reason="submit_failed", message=err or "failed to submit task",
                  target=("pipeline", p.keyname))  # fmt: skip
        return helper.send_error(err or "failed to submit task", 400)

    log2.ok("pipeline.run", target=("pipeline", p.keyname),
            extra={"schema": schema_names, "dryrun": dryrun, "handle": handle})  # fmt: skip

    task_url = request.build_absolute_uri(reverse("api:api_task_detail", args=[handle]))
    reply = {
        "pipeline": p.keyname,
        "dryrun": dryrun,
        "handle": handle,
        "task_url": task_url,
    }
    return helper.send_response(request, reply, 202)
