from __future__ import annotations

import hashlib
import json
from typing import Any, Dict, Optional

from src.fmatch.ingest.connector_sdk.base import ConnectorBase, FetchResult


class SireneDiffConnector(ConnectorBase):
    """Daily SIRENE diff ingestion (bulk delta API)."""

    def __init__(self, http_client: Any, diff_endpoint: str) -> None:
        self.http = http_client
        self.diff_endpoint = diff_endpoint

    def checkpoint_key(self) -> str:
        return "SIRENE"

    def fetch(
        self,
        *,
        batch_id: Optional[str] = None,
        next_token: Optional[str] = None,
        resume: bool = False,
    ) -> FetchResult:
        params = {"cursor": next_token} if next_token else {}
        response = self.http.get(self.diff_endpoint, params=params, timeout=30)
        response.raise_for_status()
        payload = response.json()
        items = payload.get("etablissements") or payload.get("unites_legales") or []
        nxt = payload.get("next_cursor")
        return FetchResult(
            items=items, next_token=nxt, batch_id=payload.get("batch_id") or nxt
        )

    def process(self, *, item: Dict[str, Any]) -> Dict[str, Any]:
        raw = item
        sha256 = hashlib.sha256(
            json.dumps(raw, sort_keys=True).encode("utf-8")
        ).hexdigest()

        unite_legale = raw.get("uniteLegale") or {}
        siren = raw.get("siren") or unite_legale.get("siren") or ""
        legal_name = (
            unite_legale.get("denominationUniteLegale")
            or raw.get("denominationUniteLegale")
            or ""
        )
        admin_state = unite_legale.get("etatAdministratifUniteLegale") or raw.get(
            "etatAdministratifUniteLegale"
        )
        if admin_state == "A":
            status = "active"
        elif admin_state == "C":
            status = "dissolved"
        else:
            status = "unknown"

        seen_at = (
            unite_legale.get("dateDernierTraitementUniteLegale")
            or raw.get("dateDernierTraitementUniteLegale")
            or raw.get("dateDernierTraitementEtablissement")
        )

        source_event = {
            "source": "SIRENE",
            "jurisdiction": "FR",
            "raw_id": str(siren),
            "raw_payload": raw,
            "seen_at": seen_at,
            "sha256": sha256,
            "license_tag": "redistributable",
        }

        normalized_entity = {
            "legal_name": legal_name,
            "country_code": "FR",
            "status": status,
            "ids": [{"type": "SIREN", "value": str(siren)}] if siren else [],
            "urls": [],
            "updated_at": seen_at,
        }

        status_type = "status:dissolved" if status == "dissolved" else "status"
        evidence = [
            {
                "entity_key": sha256,
                "source": "SIRENE",
                "evidence_type": "authority_id",
                "payload": {"siren": siren},
                "seen_at": seen_at,
                "license_tag": "redistributable",
            },
            {
                "entity_key": sha256,
                "source": "SIRENE",
                "evidence_type": status_type,
                "payload": {"status": status},
                "seen_at": seen_at,
                "license_tag": "redistributable",
            },
        ]

        return {
            "source_event": source_event,
            "normalized_entity": normalized_entity,
            "promotion_evidence": evidence,
        }
