from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def read(path: str) -> str:
    return (ROOT / path).read_text(encoding="utf-8")


def test_chatwoot_webhook_uses_shared_processor_and_marks_exceptions():
    webhooks = read("app/webhooks_chatwoot.py")
    persistence = read("app/persistence.py")
    assert "async def process_saved_chatwoot_raw_event" in webhooks
    assert "return await process_saved_chatwoot_raw_event(raw_event_id, payload)" in webhooks
    assert "mark_raw_event_error" in webhooks
    assert "def mark_raw_event_error" in persistence
    assert "processing_exception" in webhooks


def test_chatwoot_inbound_detection_relies_on_message_type_not_sender_contact():
    webhooks = read("app/webhooks_chatwoot.py")
    assert "message_type_text = str(message_type).lower()" in webhooks
    assert "is_outgoing = message_type_text in" in webhooks
    assert "sender.type=contact" not in webhooks
    assert "payload.message_type" in webhooks


def test_outgoing_without_matching_task_is_not_processing_error():
    webhooks = read("app/webhooks_chatwoot.py")
    assert "outgoing: {auto_complete_result.get('status')}" not in webhooks
    assert "Mensagens enviadas manualmente no Chatwoot sem task pendente" in webhooks
    assert "error=None," in webhooks


def test_reprocess_pending_chatwoot_script_exists_and_targets_incoming():
    script = read("scripts/reprocess_pending_chatwoot_raw_events.py")
    assert "process_saved_chatwoot_raw_event" in script
    assert "payload #>> '{message_type}'" in script
    assert "= 'incoming'" in script
    assert "--dry-run" in script
    assert "--include-errors" in script


def test_audit_chatwoot_ingestion_uses_message_type_and_reports_pending():
    script = read("scripts/audit_chatwoot_ingestion_gap.py")
    assert "PENDING_INCOMING_RAW_EVENT" in script
    assert "OUTGOING_IGNORED_FOR_INBOUND_AUDIT" in script
    assert "message_type=incoming" in script or "message_type" in script


def test_system_health_exposes_chatwoot_incoming_pending():
    operations = read("app/operations_service.py")
    task_service = read("app/task_service.py")
    system = read("app/admin_ui/pages/system.py")
    assert "chatwoot_incoming_pending" in operations
    assert "chatwoot_incoming_24h" in operations
    assert "chatwoot_incoming_pending" in task_service
    assert "Chatwoot inbound pendente" in system


def test_task_insert_sql_has_valid_columns_for_reprocessing_hotfix():
    task_service = read("app/task_service.py")
    insert_block = task_service.split("INSERT INTO tasks (", 1)[1].split(")\n        VALUES", 1)[0]
    assert "opportunity_id::text" not in insert_block
    assert insert_block.count("priority") == 1
    values_block = task_service.split("VALUES (", 1)[1].split(")\n        ON CONFLICT", 1)[0]
    assert values_block.count(":priority") == 1
