"""数据库 / Kafka / Redis 连接配置。

所有敏感字段从 .env 读取（项目根目录）。
本地开发：cp .env.example .env 后填值；
VPS 部署：通过 ansible / scp 把 .env 放到项目根，或 systemd EnvironmentFile= 指向它。

加新连接：在 .env 加变量，在本文件加一个 dict。
"""
import os
import platform
from pathlib import Path

try:
    from dotenv import load_dotenv
    _ENV = Path(__file__).resolve().parents[1] / ".env"
    if _ENV.exists():
        load_dotenv(_ENV)
except ImportError:
    # python-dotenv 没装也不挂：VPS 上靠 systemd 直接 export 也行
    pass


def _env(key, default=None, *, required=False):
    val = os.getenv(key, default)
    if required and not val:
        raise RuntimeError(f"environment variable {key!r} is required but missing")
    return val


def _env_int(key, default):
    return int(os.getenv(key, default))


_IS_WIN = platform.system().lower() == "windows"


# =========================================================
# 表名映射（不是密码，直接列在这）
# =========================================================
DB_REQUESTS_ASIN_PARAMS = {
    "db_syn": "us_all_syn_st",
    "db_variat": "us_variat",
    "db_cookies": "us_cookies",
    "db_us_erp_asin_syn": "us_erp_asin_syn",
    "db_us_erp_asin": "us_erp_asin",
    "db_seller_account_syn": "us_seller_account_syn",
    "db_seller_asin_account": "us_seller_asin_account",
    "db_asin_image": "us_asin_image",
    "db_seller_account_feedback_5000_asin_syn": "us_seller_account_feedback_5000_asin_syn",
    "db_amazon_seller_account": "amazon_seller_account",
    "db_ip_16yun": "ip_16yun",
    "db_request_param_val": "us_request_param_val",
    "db_seller_account_feedback": "us_seller_account_feedback",
    "db_self_asin_detail": "us_self_asin_detail",
    "db_seller_account_product_syn": "us_seller_account_product_syn",
    "db_seller_account_feedback_new": "us_seller_account_feedback_report",
    "db_competitive_aisn_syn": "us_competitive_aisn_syn",
    "db_competitive_aisn": "us_competitive_aisn",
    "db_asin_detail_product": "fr_seller_asin_product",
    "db_search_term": "us_search_term",
    "db_variation_total": "us_variation_total",
    "db_asin_star": "uk_asin_star",
    "db_asin_add_cart": "us_asin_fb_together",
    "db_brand_asin": "us_brand_asin",
    "db_bs_category_asin_detail": "fr_bs_category_asin_detail",
    "db_asin_of_concern": "us_asin_of_concern",
    "db_potential_product_asin_syn": "us_potential_product_asin_syn",
    "db_potential_product_asin": "us_potential_product_asin",
    "db_user_collection_syn": "user_collection_syn",
    "db_self_product_detail": "us_self_product_detail",
    "int_threading_num": 9,
    "if_ip_num_proxy": 100,
    "if_ip_num": 20,
    "requests_timeout": 15,
    "de_requests_timeout": 15,
    "de_int_threading_num": 8,
    "feedback_threading_num": 8,
}

DB_SEARCH_TERM_PARAMS_SPIDER = {
    "db_search_term": "us_search_term",
    "db_asin_detail_simply": "us_asin_detail_simply",
    "db_search_term_serverip": "us_search_term_serverip",
    "db_search_term_zr": "us_search_term_rank_zr",
    "db_search_term_sp": "us_search_term_rank_sp",
    "db_search_term_sb": "us_search_term_rank_sb",
    "db_search_term_ac": "us_search_term_rank_ac",
    "db_search_term_bs": "us_search_term_rank_bs",
    "db_search_term_er": "us_search_term_rank_er",
    "db_search_term_hr": "us_search_term_rank_hr",
    "db_search_term_tr": "us_search_term_rank_tr",
    "db_other_search_term": "us_other_search_term",
    "us_brand_analytics": "us_brand_analytics",
}

DB_SEARCH_TERM_PARAMS_SPIDER_MYSQL = {
    **DB_SEARCH_TERM_PARAMS_SPIDER,
    "db_potential_product_st_syn": "us_potential_product_st_syn",
    "db_potential_product_st": "us_potential_product_st",
}


# =========================================================
# 连接字典（密码从 .env 读）
# =========================================================
DB_CONN_DICT = {
    "mysql_host": _env("MYSQL_HOST", required=True),
    "mysql_port": _env_int("MYSQL_PORT", 3306),
    "mysql_db":   _env("MYSQL_DB", "selection"),
    "mysql_user": _env("MYSQL_USER", required=True),
    "mysql_pwd":  _env("MYSQL_PWD",  required=True),
}

PG_CONN_DICT = {
    "pg_host": _env("PG14_HOST_WIN" if _IS_WIN else "PG14_HOST_LINUX", required=True),
    "pg_port": _env_int("PG14_PORT_WIN" if _IS_WIN else "PG14_PORT_LINUX",
                        5433 if _IS_WIN else 54328),
    "pg_db":   _env("PG14_DB", "selection"),
    "pg_user": _env("PG14_USER", required=True),
    "pg_pwd":  _env("PG14_PWD",  required=True),
}

DORIS_CONN = {
    "mysql_host": _env("DORIS_HOST", required=True),
    "mysql_port": _env_int("DORIS_PORT", 49030),
    "mysql_db":   _env("DORIS_DB",   "us_spider"),
    "mysql_user": _env("DORIS_USER", required=True),
    "mysql_pwd":  _env("DORIS_PWD",  required=True),
}

DORIS_ADV_DIRECT_CONN = {
    "host":     _env("DORIS_ADV_HOST", required=True),
    "port":     _env_int("DORIS_ADV_PORT", 29030),
    "user":     _env("DORIS_ADV_USER", required=True),
    "password": _env("DORIS_ADV_PWD",  required=True),
    "database": _env("DORIS_ADV_DB", "advertising_manager"),
    "charset":  "utf8mb4",
}

PG_READONLY_CONN = {
    "host":     _env("PG14_READONLY_HOST", required=True),
    "port":     _env_int("PG14_READONLY_PORT", 54328),
    "user":     _env("PG14_READONLY_USER", required=True),
    "password": _env("PG14_READONLY_PWD",  required=True),
}

REDIS_CONN = {
    "redis_host": _env("REDIS_HOST", required=True),
    "redis_port": _env_int("REDIS_PORT", 6379),
    "redis_pwd":  _env("REDIS_PWD",  required=True),
    "redis_db":   _env_int("REDIS_DB", 14),
}

starrocks_CONN = {
    "mysql_host": _env("STARROCKS_HOST_WIN" if _IS_WIN else "STARROCKS_HOST_LINUX",
                       required=True),
    "mysql_port": _env_int("STARROCKS_PORT", 19030),
    "mysql_db":   _env("STARROCKS_DB", "us_spider"),
    "mysql_user": _env("STARROCKS_USER", required=True),
    "mysql_pwd":  _env("STARROCKS_PWD",  required=True),
}
