"""close_pipeline - close a TaskPipeline by exception.

Usage:
    python manage.py close_pipeline --code CH-9-BOOK --reason "ingested before pipeline existed"
    python manage.py close_pipeline --code CH-9-BOOK --reason "..." --dry-run

Marks every unresolved StudentTask of the pipeline (ASSIGNED / IN_PROGRESS)
as SKIPPED with the given reason, and marks the pipeline DONE with
stages_completed set to all nine stages. Writes ONE PortalFeatureLog
entry with the reason.

Standards: PMBOK 6.6 (Control Scope); Cooper Stage-Gate (gate closure by
  exception); ITIL 4 Change Enablement (one audited closure event);
  ISO 21500:2021 4.3.3 (sequence resolved); Rule 9 (status change only,
  no deletion); ISO 27001 A.8.15 (logged).
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from exams.models import TaskPipeline, StudentTask, PortalFeatureLog


class Command(BaseCommand):
    help = "Close a TaskPipeline by exception (mark unresolved tasks SKIPPED)."

    def add_arguments(self, parser):
        parser.add_argument("--code", type=str, required=True)
        parser.add_argument("--reason", type=str, required=True)
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        code = (options["code"] or "").strip().upper()
        reason = (options["reason"] or "").strip()[:300]
        dry = options["dry_run"]
        if not code or not reason:
            raise CommandError("--code and --reason are required")

        try:
            pipe = TaskPipeline.objects.get(paper_code=code)
        except TaskPipeline.DoesNotExist:
            raise CommandError("pipeline not found: " + code)

        unresolved = StudentTask.objects.filter(
            pipeline=pipe,
            status__in=["ASSIGNED", "IN_PROGRESS"],
        )
        n_unresolved = unresolved.count()

        self.stdout.write("pipeline: " + code
                          + " | stage " + str(pipe.current_stage)
                          + " | status " + pipe.status)
        self.stdout.write("unresolved tasks: " + str(n_unresolved))
        for t in unresolved.order_by("pipeline_stage", "student__code", "id")[:8]:
            self.stdout.write("  " + t.student.code + " | "
                              + t.task_type + " | " + t.task_ref
                              + " | stage " + str(t.pipeline_stage or "?"))
        if n_unresolved > 8:
            self.stdout.write("  ... " + str(n_unresolved - 8) + " more")

        if dry:
            self.stdout.write("(DRY RUN - nothing written)")
            return

        with transaction.atomic():
            n_skipped = unresolved.update(
                status="SKIPPED",
                ingest_error="Closed by exception: " + reason,
            )
            pipe.stages_completed = [1, 2, 3, 4, 5, 6, 7, 8, 9]
            pipe.current_stage = 9
            pipe.status = "DONE"
            pipe.save(update_fields=["stages_completed", "current_stage", "status"])

            PortalFeatureLog.objects.create(
                key="pipeline_close." + code,
                old_enabled=True, new_enabled=False,
                changed_by=None,
                note="closed by exception: " + reason
                     + " | tasks skipped: " + str(n_skipped),
            )

        self.stdout.write("closed " + code + " | skipped " + str(n_skipped) + " tasks")
        self.stdout.write("reason: " + reason)
