from __future__ import annotations

import logging
import os
from pathlib import Path
from typing import Any, Dict, Optional

import requests

from src.fmatch.ingest.connectors.sirene_diff import SireneDiffConnector

LOGGER = logging.getLogger(__name__)
CHECKPOINT_DIR = Path(os.getenv("FM_CHECKPOINT_DIR", "state/checkpoints"))
CHECKPOINT_DIR.mkdir(parents=True, exist_ok=True)
CHECKPOINT_FILE = CHECKPOINT_DIR / "sirene.json"


def load_checkpoint() -> Optional[str]:
    if CHECKPOINT_FILE.exists():
        return CHECKPOINT_FILE.read_text(encoding="utf-8") or None
    return None


def save_checkpoint(token: Optional[str]) -> None:
    if token is None:
        return
    CHECKPOINT_FILE.write_text(token, encoding="utf-8")


def persist_artifacts(artifacts: Dict[str, Any]) -> None:
    """TODO: Persist SIRENE artifacts into ingestion sinks."""
    LOGGER.info("Prepared SIRENE artifact for %s", artifacts["source_event"]["raw_id"])


def main() -> None:
    logging.basicConfig(level=logging.INFO)
    session = requests.Session()
    endpoint = os.getenv(
        "SIRENE_DIFF_ENDPOINT", "https://api.insee.fr/entreprises/sirene/V3/siren"
    )
    connector = SireneDiffConnector(session, diff_endpoint=endpoint)
    next_token = load_checkpoint()

    batch = connector.fetch(next_token=next_token)
    items = list(batch.items)
    LOGGER.info("Fetched %s SIRENE records (next=%s)", len(items), batch.next_token)
    for item in items:
        artifacts = connector.process(item=item)
        persist_artifacts(artifacts)

    if batch.next_token:
        save_checkpoint(batch.next_token)


if __name__ == "__main__":
    main()
