import json
import os
from pathlib import Path
from urllib.parse import quote_plus


BASE_DIR = Path(__file__).resolve().parents[1]
MYSQL_CONFIG_PATH = BASE_DIR / "mysqlconfig.json"


def load_mysql_config() -> dict:
    if not MYSQL_CONFIG_PATH.exists():
        raise FileNotFoundError(f"未找到 MySQL 配置文件: {MYSQL_CONFIG_PATH}")
    with MYSQL_CONFIG_PATH.open("r", encoding="utf-8-sig") as file:
        return json.load(file)


def build_mysql_uri(mysql_cfg: dict) -> str:
    user = mysql_cfg["user"]
    password = quote_plus(mysql_cfg["password"])
    host = mysql_cfg.get("host", "127.0.0.1")
    port = mysql_cfg.get("port", 3306)
    database = mysql_cfg["database"]
    charset = mysql_cfg.get("charset", "utf8mb4")
    return f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}?charset={charset}"


class Config:
    MYSQL_CONFIG = load_mysql_config()
    SQLALCHEMY_DATABASE_URI = build_mysql_uri(MYSQL_CONFIG)
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "replace-this-jwt-secret-key-in-production")
    SECRET_KEY = os.getenv("FLASK_SECRET_KEY", "replace-this-flask-secret-key-in-production")

    SPAM_DATASET_PATH = str(BASE_DIR / "seed" / "spam_samples_seed.json")
    NB_MODEL_PATH = str(BASE_DIR / "models" / "spam_nb_model.joblib")
    UPLOAD_FOLDER = str(BASE_DIR / "uploads")
