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_v4925_has_autonomous_fiscal_enrichment_service_and_schema():
    service = read("app/fiscal_enrichment_service.py")
    assert "def ensure_fiscal_enrichment_schema" in service
    assert "external_company_cache" in service
    assert "fiscal_customer_suggestions" in service
    assert "fiscal_enrichment_runs" in service
    assert "def enrich_open_opportunities" in service
    assert "def enrich_opportunity" in service
    assert "contactos/search" in service
    assert "empresas/domain" in service
    assert "empresas/nif" in service
    assert "POST" in service or "_http_json(\"POST\"" in service or "batch" in service


def test_v4925_pipeline_runs_enrichment_before_reconciliation_sync():
    sync = read("app/external_reconciliation_sync.py")
    block = sync.split("async def sync_all_external_reconciliation_candidates", 1)[1]
    assert "enrich_open_opportunities" in block
    assert block.index("enrich_open_opportunities") < block.index("sync_external_fiscal_customers_for_reconciliation")
    assert "enrichment_auto_applied" in block
    assert "enrichment_suggested" in block


def test_v4925_opportunity_creation_triggers_best_effort_enrichment():
    service = read("app/opportunity_service.py")
    block = service.split("def upsert_opportunity_for_task", 1)[1].split("def advance_opportunity_after_task_done", 1)[0]
    assert "from app.fiscal_enrichment_service import enrich_opportunity" in block
    assert "enrich_opportunity(opportunity_id, apply_safe=True)" in block
    assert "except Exception" in block


def test_v4925_ui_exposes_enrichment_actions():
    opp = read("app/admin_ui/pages/opportunities.py")
    recon = read("app/admin_ui/pages/reconciliation.py")
    assert "/opportunities/{opportunity_id}/fiscal-enrich" in opp
    assert "/fiscal-suggestions/{suggestion_id}/accept" in opp
    assert "Sugestões fiscais" in opp
    assert "/reconciliation/enrich-fiscal" in recon
    assert "Enriquecer oportunidades" in recon


def test_v4925_scripts_and_settings_exist():
    assert (ROOT / "scripts/enrich_fiscal_customers.py").exists()
    assert (ROOT / "scripts/run_reconciliation_pipeline.py").exists()
    config = read("app/config.py")
    assert "external_company_lookup_enabled" in config
    assert "external_company_lookup_base_url" in config
    assert "external_company_lookup_api_key" in config
