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.opencorporates import OpenCorporatesConnector

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 / "opencorp.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: Integrate with ingestion sinks (source_event/normalized/evidence writers)."""
    LOGGER.info("Prepared artifacts for %s", artifacts["source_event"]["raw_id"])


def main() -> None:
    logging.basicConfig(level=logging.INFO)
    session = requests.Session()
    since_hours = int(os.getenv("OPENCO_SINCE_HOURS", "6"))
    connector = OpenCorporatesConnector(session, since_hours=since_hours)
    next_token = load_checkpoint()

    batch = connector.fetch(next_token=next_token)
    items = list(batch.items)
    LOGGER.info(
        "Fetched %s OpenCorporates items (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()
