"""
Test-only helper: print the champion/staff tokens for a complaint's
department-investigation flow, so Playwright (Node) can build the token URLs.

Usage:
  manage.py get_e2e_token <complaint_id> [explanation|investigation]

Prints plain text:
  explanation_token=<token>          (champion explanation / start-investigation / review URL)
  investigation_token=<token> <staff_email>   (per-staff answer token)

This is a local CLI tool for E2E tests; it exposes nothing in the web app.
"""

from django.core.management.base import BaseCommand, CommandError

from apps.complaints.models import Complaint, ComplaintExplanation


class Command(BaseCommand):
    help = "Print champion/staff investigation tokens for a complaint (E2E test helper)."

    def add_arguments(self, parser):
        parser.add_argument("complaint_id", help="Complaint UUID")
        parser.add_argument(
            "which",
            nargs="?",
            default="all",
            choices=["all", "explanation", "investigation"],
            help="Which tokens to print",
        )

    def handle(self, *args, **options):
        cid = options["complaint_id"]
        which = options["which"]
        try:
            complaint = Complaint.objects.get(id=cid)
        except (Complaint.DoesNotExist, ValueError) as exc:
            raise CommandError(f"Complaint {cid} not found: {exc}")

        if which in ("all", "explanation"):
            expl = ComplaintExplanation.objects.filter(complaint=complaint).order_by("-created_at").first()
            if expl:
                print(f"explanation_token={expl.token} used={expl.is_used}")
            else:
                print("explanation_token=NONE")

        if which in ("all", "investigation"):
            # Investigation responses (staff answer tokens) via the investigation models
            try:
                from apps.complaints.models import (
                    ChampionInvestigation,
                    InvestigationResponse,
                )
            except ImportError:
                print("investigation_models=UNAVAILABLE")
                return
            inv = ChampionInvestigation.objects.filter(complaint=complaint).order_by("-created_at").first()
            if not inv:
                print("investigation_token=NONE")
                return
            print(f"investigation_status={inv.status}")
            for ir in InvestigationResponse.objects.filter(investigation=inv):
                staff_email = ir.staff.user.email if ir.staff and ir.staff.user else (ir.staff_id or "?")
                print(f"investigation_token={ir.token} staff={staff_email} completed={ir.is_completed}")
