import os
import sys
from datetime import timedelta


def get_base_path():
    """获取运行时路径 (兼容打包后的 exe 和开发环境)"""
    if getattr(sys, 'frozen', False):
        if hasattr(sys, '_MEIPASS'):
            return sys._MEIPASS
        else:
            return os.path.dirname(os.path.abspath(sys.executable))
    return os.path.dirname(os.path.abspath(__file__))


class Config:
    BASE_DIR = get_base_path()
    INSTANCE_FOLDER = os.path.join(BASE_DIR, 'instance')

    # 确保 instance 目录存在
    if not os.path.exists(INSTANCE_FOLDER):
        os.makedirs(INSTANCE_FOLDER, exist_ok=True)

    # 静态文件路径
    STATIC_FOLDER = os.path.join(BASE_DIR, 'web_dist')

    # --- 数据库配置 (整合了 app.py 的逻辑) ---
    # 1. 主数据库 (Device, Log 等)
    DB_DEVICES_PATH = os.path.join(INSTANCE_FOLDER, 'devices.db')
    SQLALCHEMY_DATABASE_URI = f'sqlite:///{DB_DEVICES_PATH}'

    # 2. 用户数据库 (User, Permission 等，绑定到 users_db)
    DB_USERS_PATH = os.path.join(INSTANCE_FOLDER, 'users.db')
    SQLALCHEMY_BINDS = {
        'users_db': f'sqlite:///{DB_USERS_PATH}'
    }

    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # --- 🔴 关键修复：JWT 配置 (必须设置) ---
    JWT_SECRET_KEY = 'super-secret-key-change-this-in-prod-2026'
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(days=1)  # Token 1天有效

    # --- 定时任务配置 ---
    SCHEDULER_API_ENABLED = True
    SCHEDULER_TIMEZONE = "Asia/Shanghai"

    # --- 爬虫配置 (保留你原有的配置) ---
    CRAWLER_CONFIG = {
        "106": {
            "base_url": "http://106.75.72.40:7500/api/proxy/tcp",
            "primary_auth": "Basic YWRtaW46bGljYWhr",
            "login_payload": {"username": "admin", "password": "licahk", "recaptcha": ""}
        },
        "82": {
            "base_url": "http://82.156.1.111/weather/php",
            "login": {'username': 'renlixin', 'password': 'licahk', 'login': '123'}
        }
    }