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_reconciliation_page_has_safe_rebuild_button():
    page = read("app/admin_ui/pages/reconciliation.py")
    service = read("app/reconciliation_service.py")

    assert '/reconciliation/rebuild' in page
    assert 'Apagar e correr novamente' in page
    assert 'Não apaga clientes, oportunidades nem documentos reais' in page
    assert 'reset_generated_reconciliation_items' in service
    assert 'opportunity_id IS NULL' in service
    assert 'CREATE TABLE {backup_table} AS SELECT * FROM reconciliation_items' in service


def test_rebuild_endpoint_resets_then_syncs_external_candidates():
    page = read("app/admin_ui/pages/reconciliation.py")

    rebuild_block = page.split('@router.post("/reconciliation/rebuild")', 1)[1].split('@router.post("/reconciliation/cleanup-window")', 1)[0]
    assert 'reset_generated_reconciliation_items' in rebuild_block
    assert 'apply=True' in rebuild_block
    assert 'sync_all_external_reconciliation_candidates' in rebuild_block
    assert 'limit=200' in rebuild_block
