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_v496_reconciliation_schema_stores_customer_tax_id():
    service = read("app/reconciliation_service.py")

    assert "customer_tax_id TEXT" in service
    assert "idx_reconciliation_customer_tax_id" in service
    assert "customer_tax_id: Optional[str]" in service
    assert "customer_tax_id = _normalize_tax_id(customer_tax_id)" in service


def test_v496_nif_exact_match_is_primary_suggestion_signal():
    service = read("app/reconciliation_service.py")

    assert "NIF exato" in service
    assert "COALESCE(lc.tax_id, '') = :customer_tax_id" in service
    assert "THEN 90 ELSE 0" in service
    assert "if not any([customer_id, customer_tax_id, customer_email, customer_name, amount_value])" in service


def test_v496_external_sync_extracts_tax_id_from_jasmin_and_odoo():
    sync = read("app/external_reconciliation_sync.py")

    assert "def _customer_tax_id" in sync
    assert "companyTaxID" in sync
    assert "buyerCustomerPartyTaxID" in sync
    assert '"customer_tax_id": _customer_tax_id(record)' in sync
    assert 'client.search_read(\n            "res.partner"' in sync
    assert 'record["partner_vat"]' in sync


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

    assert "NIF {esc(item.get(\"customer_tax_id\"))}" in page
