"""
Configuration for the v2 ops-ingestion sink.

v2 keeps the existing scrapers unchanged (they still write per-retailer SQLite
DBs); only the sink changes: instead of load_mysql.py, results are POSTed to the
Baskit Ops ingestion API (/ingest/v1/*).

This module reuses the parent pipeline `config.py` for SQLite DB paths and the
retailer list, and adds the OPS_* settings loaded from pipeline/v2/.env.
"""
from __future__ import annotations

import os
import sys
from pathlib import Path

from dotenv import load_dotenv

# Reuse the parent pipeline config (DB paths, RETAILERS) without duplicating it.
V2_ROOT = Path(__file__).resolve().parent
PIPELINE_ROOT = V2_ROOT.parent
if str(PIPELINE_ROOT) not in sys.path:
    sys.path.insert(0, str(PIPELINE_ROOT))

import config as base_config  # noqa: E402  (path set above)

# v2-specific env (does not override the parent pipeline/.env).
load_dotenv(V2_ROOT / ".env")


def _bool(key: str, default: bool) -> bool:
    return os.environ.get(key, str(default)).lower() in ("1", "true", "yes", "on")


def _int(key: str, default: int) -> int:
    return int(os.environ.get(key, str(default)))


def _float(key: str, default: float) -> float:
    return float(os.environ.get(key, str(default)))


# Ingestion API target (INGEST_SERVICE_KEY matches the Ops server env name)
BASE_URL = os.environ.get("OPS_INGEST_BASE_URL", "https://baskitops.appnotify.co.za").rstrip("/")
SERVICE_KEY = os.environ.get("OPS_SERVICE_KEY") or os.environ.get("INGEST_SERVICE_KEY", "")

# HTTP behaviour
TIMEOUT = _float("OPS_TIMEOUT", 120.0)
BATCH_SIZE = _int("OPS_BATCH_SIZE", 200)
MAX_RETRIES = _int("OPS_MAX_RETRIES", 3)
RETRY_BACKOFF = _float("OPS_RETRY_BACKOFF", 2.0)
# The prod cert chain may be flagged by Windows schannel; allow opting out of
# verification for that environment. Defaults to verifying.
VERIFY_TLS = _bool("OPS_VERIFY_TLS", True)

# Scraper name -> Baskit Ops retailer_id (see RetailerSeeder: pnp=1, sixty60=2,
# woolworths=3, spar=4). "checkers" is the Sixty60 catalog => retailer 2.
RETAILER_IDS = {
    "pnp": _int("OPS_RETAILER_ID_PNP", 1),
    "checkers": _int("OPS_RETAILER_ID_CHECKERS", 2),
    "woolworths": _int("OPS_RETAILER_ID_WOOLWORTHS", 3),
    "spar": _int("OPS_RETAILER_ID_SPAR", 4),
}

# SQLite source DB per scraper (from the parent pipeline config).
RETAILER_DBS = {
    "pnp": base_config.PNP_DB,
    "checkers": base_config.CHECKERS_DB,
    "woolworths": base_config.WOOLWORTHS_DB,
}

# Which retailers to push (reuses BASKIT_RETAILERS from the parent config).
RETAILERS = base_config.RETAILERS


def require_service_key() -> str:
    """Return the configured service key or raise a clear error."""
    if not SERVICE_KEY:
        raise SystemExit(
            "OPS_SERVICE_KEY (or INGEST_SERVICE_KEY) is not set. "
            "Add it to pipeline/v2/.env or the worker environment."
        )
    return SERVICE_KEY
