"""Read-only milestone evidence for an already authorized ServiceCase.

These display states never authorize an operation or replace service preconditions.
No notes, diagnostic findings or recipient identity documents are disclosed here.
"""
from apps.commercial import payment_queries
from apps.service import engineer_queries, diagnostic_queries, repair_queries, quality_control_queries
from apps.sla.queries import records
from . import queries


def job_overview(actor, case, quotation):
    from .job_workspace import access, sections
    flags = access(actor, case)
    def can(permission):
        return flags[{"commercial.view_servicequotation": "quote", "commercial.view_servicepayment": "payment"}[permission]]

    steps = []
    def step(label, state, evidence):
        steps.append(dict(label=label, state=state, evidence=evidence))

    step("Intake", "completed", case.received_at)
    handover = getattr(case, "handover", None)
    assignment = engineer_queries.engineer_assignment_history(case).order_by("-assigned_at", "-pk").first()
    step("Assignment", "completed" if assignment and assignment.ended_at and handover else
         "current" if assignment and not assignment.ended_at else "pending",
         "Assignment ended at handover" if assignment and assignment.ended_at and handover else
         "No current assignment; previous assignment ended" if assignment and assignment.ended_at else
         assignment.engineer.get_username() if assignment else "No current assignment")
    diagnosis = diagnostic_queries.diagnostic_assessment_history(case).order_by("-started_at", "-pk").first()
    step("Diagnosis", "completed" if diagnosis and diagnosis.completed_at else
         "current" if diagnosis and not diagnosis.abandoned_at else "pending",
         diagnosis.completed_at if diagnosis and diagnosis.completed_at else "No completed current assessment")
    if can("commercial.view_servicequotation"):
        state = quotation.status if quotation else None
        step("Quotation", "completed" if state == "APPROVED" else "blocked" if state == "REJECTED" else "pending",
             f"Revision {quotation.revision}: {state}" if quotation else "No quotation recorded; coverage is not inferred")
    else:
        step("Quotation", "unavailable", "Commercial evidence is not available with your permissions")
    repair = repair_queries.repair_execution_history(case).order_by("-started_at", "-pk").first()
    step("Repair", "completed" if repair and repair.status == "COMPLETED" and repair.outcome == "REPAIRED" else
         "blocked" if repair and repair.status == "COMPLETED" and repair.outcome == "NOT_REPAIRED" else
         "current" if repair and repair.status == "OPEN" else "pending",
         repair.outcome or repair.status if repair else "No repair execution recorded")
    qc_visible = quality_control_queries.quality_control_visible_cases(actor).filter(pk=case.pk).exists()
    if qc_visible:
        qc = quality_control_queries.quality_control_history(case).order_by("-started_at", "-pk").first()
        step("QC", "completed" if qc and qc.outcome == "PASSED" else "rework" if qc and qc.outcome == "FAILED" else
             "current" if qc and qc.status == "IN_PROGRESS" else "pending",
             qc.outcome or qc.status if qc else "No quality control recorded")
    else:
        step("QC", "unavailable", "QC evidence is not available in your inspector scope")
    release = getattr(case, "delivery_release", None)
    step("Ready", "completed" if release else "pending", release.readied_at if release else "No delivery release recorded")
    settlement = payment_queries.settlement_invoices(actor=actor).filter(service_case=case, status="FINALIZED").first()
    if settlement:
        if settlement.balance_due == 0:
            step("Payment", "completed", "No customer liability" if settlement.customer_pay_total == 0 else "Customer balance settled")
        else:
            released = settlement.release_limit >= settlement.balance_due
            step("Payment", "current" if released else "blocked",
                 f"{settlement.currency} {settlement.balance_due} outstanding" +
                 ("; authorized due-release, balance remains due" if released else "; financial clearance required"))
    else:
        step("Payment", "pending" if can("commercial.view_servicepayment") else "unavailable",
             "No finalized invoice in your authorized payment scope; payment or coverage is not inferred")
    closure = getattr(case, "closure", None)
    step("Handover", "completed" if handover else "pending", "Handover recorded" if handover else "No handover recorded")
    step("Closed", "completed" if closure else "pending", "Closure recorded" if closure else "No closure recorded")
    sla = records(actor).filter(service_case=case).first()
    visible_device = queries.devices(actor).filter(pk=case.device_id).first()
    identifiers = list(visible_device.identifiers.filter(is_active=True)) if visible_device else []
    return dict(steps=steps, engineer=assignment.engineer.get_username() if assignment and not assignment.ended_at else "Unassigned",
                sla=sla.sla_state.replace("_", " ").title() if sla else "No SLA evidence in your authorized scope",
                identifiers=identifiers, cancelled=case.status == "CANCELLED", sections=sections(case, flags, qc_visible))
