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_auto_complete_has_hard_policy_deny_list_even_when_env_is_configured():
    service = read("app/task_service.py")
    assert "never_auto_complete_codes" in service
    assert '"CONFIRM_PAYMENT"' in service
    assert '"CONFIRM_PAYMENT_AND_PREPARE_SHIPMENT"' in service
    assert '"REMOVE_FROM_LIST"' in service
    assert "blocked_by_policy" in service
    assert "ClientFlow auto-complete policy ignored action_codes" in service


def test_outbox_worker_claims_rows_with_skip_locked_instead_of_listing_pending():
    service = read("app/integration_outbox_service.py")
    script = read("scripts/process_outbox.py")
    assert "def claim_pending_outbox" in service
    assert "FOR UPDATE SKIP LOCKED" in service
    assert "status = 'processing'" in service
    assert "locked_at = now()" in service
    assert "lock_owner = :lock_owner" in service
    assert "claim_pending_outbox" in script
    assert "list_pending_outbox" not in script
    assert "OUTBOX_WORKER_ID" in script


def test_outbox_completion_releases_processing_lock():
    service = read("app/integration_outbox_service.py")
    assert "def mark_outbox_sent" in service
    assert "locked_at = NULL" in service
    assert "lock_owner = NULL" in service
    assert "def mark_outbox_failed" in service


def test_system_health_exposes_operational_metrics_and_autocomplete_config():
    ops = read("app/operations_service.py")
    assert "operational_metrics" in ops
    assert "tasks_auto_completed_24h" in ops
    assert "ambiguous_opportunity_tasks" in ops
    assert "outbox_processing_stale" in ops
    assert "chatwoot_auto_complete_action_codes" in ops


def test_tasks_route_still_exists_but_is_not_primary_navigation():
    operations_page = read("app/admin_ui/pages/operations.py")
    tasks_page = read("app/admin_ui/pages/tasks.py")
    navigation = read("app/admin_ui/navigation.py")
    primary_start = navigation.index("PRIMARY_NAV_ITEMS")
    primary_end = navigation.index("ADMIN_NAV_ITEMS", primary_start)
    primary_nav = navigation[primary_start:primary_end]
    assert 'NavItem("tasks", "/tasks"' not in primary_nav
    assert 'NavItem("tasks", "/tasks", "bi-list-check", "Tasks", "admin")' in navigation
    assert '@router.get("/tasks", response_class=HTMLResponse)' in tasks_page
    assert "Ver lista completa de tarefas" in operations_page
