import asyncio
import json
import os
import types

from src.fmatch.saas.workers.api_match_worker import ApiMatchWorker


class _Repo:
    def __init__(self, cfg):
        self._cfg = cfg
        self.updated = []
    async def get_job(self, job_id):
        o = types.SimpleNamespace()
        o.config = self._cfg
        return o
    async def update_job_status(self, job_id, status, results=None, error=None, results_path=None, matches_found=None):
        self.updated.append((status, results, error))


class _Storage:
    def __init__(self, body):
        self._body = body
    async def read(self, key):
        return self._body


def test_worker_hmac_callback(monkeypatch):
    os.environ['WEBHOOK_HMAC_SECRET'] = 'secret123'
    body = json.dumps({
        'profile': 'balanced',
        'body': {'source': {'Company': 'Acme'}, 'candidates': [{'Name': 'Acme Inc'}], 'options': {'callback_url': 'https://callback'}}
    }).encode()
    worker = ApiMatchWorker(db=None, storage=_Storage(body))
    repo = _Repo({'artifact_key': 'k', 'api_key_prefix': 'kprefix'})
    worker.job_repo = repo  # type: ignore

    # Fake engine/intelligence
    import pandas as pd
    async def fake_policy(self, **kwargs):
        return {"suggest": 0.7, "auto_link": 0.8}
    async def fake_auto(self, *args, **kwargs):
        return {"field_mappings": [{"source": "Company", "reference": "Name", "algorithm": "WRatio"}]}
    async def fake_match(self, *args, **kwargs):
        df = pd.DataFrame([{"score": 0.9, "Name": "Acme Inc"}])
        class R:
            matches = df
            engine_version = 'x'
            processing_time_ms = 1
        return R()
    from src.fmatch.saas.api.intelligence_client import IntelligenceClient
    from src.fmatch.saas.services.engine_client import EngineClient
    IntelligenceClient.get_policy = fake_policy  # type: ignore
    IntelligenceClient.auto_configure = fake_auto  # type: ignore
    EngineClient.match_records = fake_match  # type: ignore

    sent = {}
    class _Httpx:
        def __init__(self, *a, **k): pass
        async def __aenter__(self): return self
        async def __aexit__(self, *a): return False
        async def post(self, url, headers=None, content=None):
            sent['url'] = url
            sent['headers'] = headers
            sent['content'] = content
            class R:
                status_code = 200
            return R()

    import httpx as _real
    monkeypatch.setattr(_real, 'AsyncClient', _Httpx, raising=False)

    asyncio.get_event_loop().run_until_complete(worker.run_job('j1', 'acct', 'balanced', options={'callback_url': 'https://callback'}))
    assert sent.get('url') == 'https://callback'
    sig = sent.get('headers', {}).get('X-Foundry-Signature', '')
    assert sig.startswith('sha256=')

