"""
Smile.One Scraper Configuration
"""

import os
import sys
from pathlib import Path

# Playwright "chrome" channel on Linux expects Google Chrome here (not apt chromium-browser).
_LINUX_GOOGLE_CHROME = Path("/opt/google/chrome/chrome")


def playwright_effective_channel() -> str | None:
    """
    If PLAYWRIGHT_CHANNEL=chrome on Linux but Chrome is not installed at the path Playwright
    uses, return None so bundled Chromium is used (after: python -m playwright install chromium).
    """
    raw = (os.getenv("PLAYWRIGHT_CHANNEL") or "").strip()
    if not raw:
        return None
    if raw.lower() == "chrome" and sys.platform.startswith("linux"):
        if not _LINUX_GOOGLE_CHROME.is_file():
            return None
    return raw
# Regional URLs - နိုင်ငံအလိုက် URL များ
REGIONS = {
    "br": "https://www.smile.one/br/",      # Brazil
    "ph": "https://www.smile.one/ph/",      # Philippines
    "my": "https://www.smile.one/my/",      # Malaysia
    "th": "https://www.smile.one/th/",      # Thailand
    "in": "https://www.smile.one/in/",      # India
}

# Merged into home list after Brazil scrape (same ML art as global catalog where possible)
_EXTRA_IMG_MLBB = "https://img.smile.one/media/catalog/product/e/s5/es5qxxw01digo5g1752654061.webp"
EXTRA_HOME_MERCHANTS = [
    {
        "name": "Mobile Legends PH",
        "url": "https://www.smile.one/ph/merchant/mobilelegends",
        "image": _EXTRA_IMG_MLBB,
    },
]

# ₱→BRL fallback when live FX API fails (~mid-market; see currency.get_php_to_brl_rate). Override: PHP_TO_BRL_RATE
DEFAULT_PHP_TO_BRL_RATE = 0.089

# MLBB PH / smile.one /ph/ — 1 PHP = X MMK (retail), direct MMK in API (no BRL). Override: PHP_TO_MMK_RATE
DEFAULT_PHP_TO_MMK_RATE = 85

# Default settings
DEFAULT_DELAY = 1.0  # seconds between requests
DEFAULT_TIMEOUT = 15

# Home list cache: if smile_one_data.json has fewer merchants than this, refresh on next /api/products load
MIN_MERCHANTS_CACHE_OK = 25

# In-memory package scrape cache (seconds) while the server process is running
PACKAGE_SCRAPE_CACHE_TTL_SEC = 300
# Persistent JSON cache for product pages — survives restarts; refresh with ?refresh=1 on product URL
PACKAGE_SCRAPE_DISK_CACHE_TTL_SEC = 604800

# Home page Playwright scroll tuning (smaller = faster, may load fewer lazy links)
HOME_SCROLL_MAX_ROUNDS = 18
HOME_SCROLL_WAIT_MS = 280
HOME_POST_LOAD_WAIT_MS = 1100
HOME_AFTER_SCROLL_WAIT_MS = 350

# Merchant package page — balance speed vs JS-rendered price grids (too short => empty packages)
PACKAGE_SCROLL_ROUNDS = 4
PACKAGE_SCROLL_STEP_WAIT_MS = 320
PACKAGE_POST_NAV_WAIT_MS = 1200
PACKAGE_AFTER_SCROLL_WAIT_MS = 400

# HTTP thread waits for background Playwright order (seconds)
ORDER_THREAD_JOIN_TIMEOUT_SEC = 45

# Node Playwright subprocess max runtime (seconds). UI polling should stay above this (see product page).
ORDER_NODE_SUBPROCESS_TIMEOUT_SEC = int(os.getenv("ORDER_NODE_SUBPROCESS_TIMEOUT_SEC", "420"))

# API rate limits (per user id or IP; override with env RATELIMIT_*)
try:
    RATELIMIT_ORDER_PER_MINUTE = int(os.getenv("RATELIMIT_ORDER_PER_MINUTE", "15"))
    RATELIMIT_ME_PER_MINUTE = int(os.getenv("RATELIMIT_ME_PER_MINUTE", "120"))
    RATELIMIT_ORDER_STATUS_PER_MINUTE = int(os.getenv("RATELIMIT_ORDER_STATUS_PER_MINUTE", "180"))
    RATELIMIT_PRODUCT_DETAILS_PER_MINUTE = int(os.getenv("RATELIMIT_PRODUCT_DETAILS_PER_MINUTE", "40"))
    RATELIMIT_DEFAULT_API_PER_MINUTE = int(os.getenv("RATELIMIT_DEFAULT_API_PER_MINUTE", "200"))
except (TypeError, ValueError):
    RATELIMIT_ORDER_PER_MINUTE = 15
    RATELIMIT_ME_PER_MINUTE = 120
    RATELIMIT_ORDER_STATUS_PER_MINUTE = 180
    RATELIMIT_PRODUCT_DETAILS_PER_MINUTE = 40
    RATELIMIT_DEFAULT_API_PER_MINUTE = 200

# API audit log: max rows kept (older rows deleted periodically)
API_AUDIT_MAX_ROWS = 50_000


def _env_bool(name: str, default: bool = False) -> bool:
    v = (os.getenv(name) or "").strip().lower()
    if not v:
        return default
    return v in ("1", "true", "yes", "on")


# Production hardening (local http://127.0.0.1 is never forced to HTTPS)
ENABLE_HSTS = _env_bool("ENABLE_HSTS", False)
FORCE_HTTPS = _env_bool("FORCE_HTTPS", False)

# Public site URL (API docs, integrations; override for staging)
PUBLIC_SITE_URL = (os.getenv("PUBLIC_SITE_URL") or "https://www.jungtzystore.shop").rstrip("/")

# Shown in UI instead of scraped "Smile.One" branding
STORE_DISPLAY_NAME = (os.getenv("STORE_DISPLAY_NAME") or "JungTzy Store").strip()

# Playwright step delays inside order_automation (seconds; override with env e.g. ORDER_SLEEP_AFTER_CLICK_SEC)
ORDER_SLEEP_AFTER_GOTO_SEC = float(os.getenv("ORDER_SLEEP_AFTER_GOTO_SEC", "0.5"))
ORDER_SLEEP_AFTER_FILL_SEC = float(os.getenv("ORDER_SLEEP_AFTER_FILL_SEC", "0.45"))
ORDER_SLEEP_AFTER_CLICK_SEC = float(os.getenv("ORDER_SLEEP_AFTER_CLICK_SEC", "0.55"))
CHECKOUT_REQ_SLEEP_SHORT_SEC = float(os.getenv("CHECKOUT_REQ_SLEEP_SHORT_SEC", "0.6"))

# Currency conversion (for UI display and package matching)
DEFAULT_MARKUP_PCT = 0.0  # no markup on top of BRL→MMK rate
# Fixed retail rate: 1 BRL -> MMK (override with env BRL_TO_MMK_RATE)
DEFAULT_BRL_TO_MMK_RATE = 815
# Optional env overrides:
# - BRL_TO_MMK_RATE: fixed FX rate (1 BRL -> MMK), overrides DEFAULT_BRL_TO_MMK_RATE
# - BRL_USE_LIVE_FX_API=1: use public FX API instead of DEFAULT_BRL_TO_MMK_RATE
# - BRL_TO_MMK_FALLBACK_RATE: if live API fails (only when BRL_USE_LIVE_FX_API=1)
