import sqlite3
import os
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class DatabaseManager:
    """
    管理 SQLite 数据库连接和初始化。
    """

    def __init__(self, db_path='data/honeypot.db'):
        """
        初始化数据库管理器。
        :param db_path: SQLite 数据库文件路径。
        """
        self.db_path = db_path
        # 确保 data 目录存在
        os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
        self.init_db()

    def get_connection(self):
        """
        获取数据库连接。
        :return: SQLite 连接对象。
        """
        conn = sqlite3.connect(self.db_path)
        # 为了让 row 可以通过列名访问
        conn.row_factory = sqlite3.Row
        return conn

    def init_db(self):
        """
        初始化数据库，创建必要的表。
        """
        try:
            with self.get_connection() as conn:
                cursor = conn.cursor()
                
                # 创建 environments 表
                # 注意：config 和 rules 字段存储 JSON 字符串
                cursor.execute('''
                    CREATE TABLE IF NOT EXISTS environments (
                        id TEXT PRIMARY KEY,
                        driver TEXT NOT NULL,
                        config TEXT NOT NULL, -- JSON string
                        status TEXT NOT NULL
                    );
                ''')
                
                # 创建 environment_rules 表 (关联表)
                # 用于存储分配给特定环境的规则
                # rule_data 存储完整的规则对象 JSON 字符串
                cursor.execute('''
                    CREATE TABLE IF NOT EXISTS environment_rules (
                        environment_id TEXT NOT NULL,
                        rule_data TEXT NOT NULL, -- JSON string of the rule object
                        rule_order INTEGER NOT NULL, -- 用于保持规则顺序
                        FOREIGN KEY (environment_id) REFERENCES environments (id) ON DELETE CASCADE
                    );
                ''')
                
                # 创建索引以提高查询效率
                cursor.execute('CREATE INDEX IF NOT EXISTS idx_env_rules_env_id ON environment_rules(environment_id);')
                
                conn.commit()
                logger.info(f"Database initialized successfully at {self.db_path}")
        except sqlite3.Error as e:
            logger.error(f"Error initializing database: {e}")
            raise

# 全局数据库管理器实例
db_manager = None

def get_db_manager():
    """
    获取全局数据库管理器实例。
    :return: DatabaseManager 实例。
    """
    global db_manager
    if db_manager is None:
        db_manager = DatabaseManager()
    return db_manager