import sys
import types
from pathlib import Path

from app.domain.opportunity_flow.evidence import build_opportunity_evidence
from app.invoice_evidence import completed_send_invoice_task_evidence

# workflow_guard only needs the engine for DB-backed functions.  Stub app.db so
# the pure evidence wrapper can be imported in environments without psycopg.
sys.modules.setdefault("app.db", types.SimpleNamespace(engine=object()))
from app.workflow_guard import _completed_send_invoice_task_evidence


def _invoice():
    return {
        "id": "f5c53585-d8be-4f6c-b69e-e36202f47559",
        "external_id": "a2d2118f-b022-4f8f-997b-0d7fa00a1945",
        "document_kind": "invoice",
        "document_number": "FA.FA2026.159",
        "role": "current",
        "is_active": True,
        "payload": {},
    }


def _noltia_task():
    return {
        "action_code": "SEND_INVOICE",
        "status": "done",
        "action": "Enviar fatura FA.FA2026.159 ao cliente",
        "note": "Enviar fatura FA.FA2026.159 ao cliente. PDF/anexo disponível.",
        "metadata": {
            # Original task context was created from the quotation.
            "document_id": "e70968b3-d58e-4f4d-864a-54c00108a7bc",
            "document_number": "ORC.ORC2026.220",
            "next_action": {
                "document_id": "e70968b3-d58e-4f4d-864a-54c00108a7bc",
                "document_number": "ORC.ORC2026.220",
            },
            # Completion guard later attached the actual invoice.
            "invoice_delivery_context": {
                "document_id": "f5c53585-d8be-4f6c-b69e-e36202f47559",
                "document_number": "FA.FA2026.159",
                "document_kind": "invoice",
                "pdf_available": True,
            },
            "done_note": "Fatura enviada ao cliente.",
        },
    }


def _task_with_reference(document_id: str, document_number: str = "FA.FA2026.159"):
    return {
        "action_code": "SEND_INVOICE",
        "status": "done",
        "action": "Enviar fatura FA.FA2026.159 ao cliente",
        "metadata": {
            "document_id": document_id,
            "document_number": document_number,
        },
    }


def test_noltia_invoice_delivery_context_supersedes_stale_quotation_context():
    assert completed_send_invoice_task_evidence([_noltia_task()], [_invoice()]) is True
    assert _completed_send_invoice_task_evidence([_noltia_task()], [_invoice()]) is True

    evidence = build_opportunity_evidence(
        {"id": "321aab34-31df-44bf-9bcd-7e7d86797598", "metadata": {}},
        linked_documents=[_invoice()],
        tasks=[_noltia_task()],
    )
    assert evidence.invoice_sent is True


def test_internal_and_jasmin_external_invoice_ids_are_both_valid():
    assert completed_send_invoice_task_evidence(
        [_task_with_reference("f5c53585-d8be-4f6c-b69e-e36202f47559")],
        [_invoice()],
    ) is True
    assert completed_send_invoice_task_evidence(
        [_task_with_reference("a2d2118f-b022-4f8f-997b-0d7fa00a1945")],
        [_invoice()],
    ) is True


def test_authoritative_invoice_delivery_context_rejects_different_invoice():
    task = _noltia_task()
    task["metadata"]["invoice_delivery_context"] = {
        "document_id": "22222222-2222-2222-2222-222222222222",
        "document_number": "FA.FA2026.999",
        "document_kind": "invoice",
    }
    assert completed_send_invoice_task_evidence([task], [_invoice()]) is False
    assert _completed_send_invoice_task_evidence([task], [_invoice()]) is False

    evidence = build_opportunity_evidence(
        {"id": "321aab34-31df-44bf-9bcd-7e7d86797598", "metadata": {}},
        linked_documents=[_invoice()],
        tasks=[task],
    )
    assert evidence.invoice_sent is False


def test_central_loader_reads_task_metadata_and_invoice_external_id():
    source = Path("app/opportunity_next_action_service.py").read_text()
    assert "created_at, metadata" in source
    assert "SELECT id::text, external_id, document_kind" in source
