"""
Central configuration for the Baskit scraping pipeline.

Loads settings from pipeline/.env (or process env). All paths default relative
to this package directory.
"""
from __future__ import annotations

import os
from pathlib import Path

from dotenv import load_dotenv

ROOT = Path(__file__).resolve().parent
load_dotenv(ROOT / ".env")


def _path(env_key: str, default: str) -> Path:
    raw = os.environ.get(env_key, default)
    p = Path(raw)
    return p if p.is_absolute() else (ROOT / p)


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


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


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


# Directories
DATA_DIR = _path("BASKIT_DATA_DIR", "data")
EXPORTS_DIR = _path("BASKIT_EXPORTS_DIR", "exports")

# SQLite working databases
PNP_DB = _path("BASKIT_PNP_DB", str(DATA_DIR / "pnp.db"))
CHECKERS_DB = _path("BASKIT_CHECKERS_DB", str(DATA_DIR / "checkers.db"))
WOOLWORTHS_DB = _path("BASKIT_WOOLWORTHS_DB", str(DATA_DIR / "woolworths.db"))
BASKIT_DB = _path("BASKIT_DB", str(DATA_DIR / "baskit.db"))

# MySQL destination (web app)
MYSQL = dict(
    host=os.environ.get("BASKIT_MYSQL_HOST", "127.0.0.1"),
    port=_int("BASKIT_MYSQL_PORT", 3306),
    user=os.environ.get("BASKIT_MYSQL_USER", "root"),
    password=os.environ.get("BASKIT_MYSQL_PASSWORD", ""),
    database=os.environ.get("BASKIT_MYSQL_DB", "baskit"),
    charset="utf8mb4",
)

# Scrape tuning
SCRAPE_DELAY = _float("BASKIT_SCRAPE_DELAY", 0.6)
CHECKERS_DELAY = _float("BASKIT_CHECKERS_DELAY", SCRAPE_DELAY)
WOOLWORTHS_DELAY = _float("BASKIT_WOOLWORTHS_DELAY", 0.5)
PNP_DELAY = _float("BASKIT_PNP_DELAY", 1.0)
PER_TERM_CAP = _int("BASKIT_PER_TERM_CAP", 100)
HEADLESS = _bool("BASKIT_HEADLESS", True)

# Pipeline orchestration
RETAILERS = [
    r.strip()
    for r in os.environ.get("BASKIT_RETAILERS", "checkers,woolworths").split(",")
    if r.strip()
]
REFRESH = _bool("BASKIT_REFRESH", True)
# PnP re-scrapes ~35k products on refresh — keep off unless you need hourly PnP prices
PNP_REFRESH = _bool("BASKIT_PNP_REFRESH", False)
RUN_MYSQL_LOAD = _bool("BASKIT_RUN_MYSQL_LOAD", True)
PIPELINE_INTERVAL_HOURS = _float("BASKIT_PIPELINE_INTERVAL_HOURS", 1.0)
# Pause between retailers in the v2 rotate loop (seconds). Each scrape already
# takes ~30–45 min, so this is a small buffer only.
ROTATE_COOLDOWN_SEC = _int("BASKIT_ROTATE_COOLDOWN_SEC", 60)
# Max retailers scraping/pushing at once in the v2 rotate loop.
ROTATE_MAX_PARALLEL = _int("BASKIT_ROTATE_MAX_PARALLEL", 2)
# If a retailer is still running after this many seconds, start the next one
# (up to ROTATE_MAX_PARALLEL). Keeps PnP from blocking Checkers/Woolworths.
ROTATE_START_AFTER_SEC = _int("BASKIT_ROTATE_START_AFTER_SEC", 45 * 60)
COMPARE_MIN_RETAILERS = _int("BASKIT_COMPARE_MIN_RETAILERS", 2)
# Optional host path to copy a pre-scraped pnp.db when the working copy is empty
PNP_SEED_PATH = os.environ.get("BASKIT_PNP_SEED_PATH", "")
# Optional: download pnp.db(.gz) when empty — gunzip applied for .gz URLs
PNP_DOWNLOAD_URL = os.environ.get("BASKIT_PNP_DOWNLOAD_URL", "")
PNP_FORCE_SEED = _bool("BASKIT_PNP_FORCE_SEED", False)

# Viewer (view_server.py)
VIEW_USER = os.environ.get("BASKIT_VIEW_USER", "baskit")
VIEW_PASSWORD = os.environ.get("BASKIT_VIEW_PASSWORD", "baskit2026")
VIEW_PORT = _int("BASKIT_VIEW_PORT", 8088)


def ensure_dirs() -> None:
    """Create data/ and exports/ if missing."""
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    EXPORTS_DIR.mkdir(parents=True, exist_ok=True)
