#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""数据库监控配置解析：与数据库连接管理统一，按连接 code 监控目标库。"""
from typing import Any, Dict, List, Optional

from sqlalchemy.ext.asyncio import AsyncSession

from core.database_connection.resolver import ConnectionResolver
from core.database_connection.service import DatabaseConnectionService
from core.database_monitor.database_collector import AsyncDatabaseCollector


def normalize_monitor_db_type(db_type: str) -> str:
    upper = (db_type or "").upper()
    if upper in ("MSSQL", "SQL SERVER"):
        return "SQLSERVER"
    return upper


def default_database_for_type(db_type: str) -> str:
    db = (db_type or "").lower()
    if db == "postgresql":
        return "postgres"
    if db == "sqlserver":
        return "master"
    if db == "oracle":
        return "ORCL"
    return ""


async def list_monitor_configs(db: AsyncSession) -> List[Dict[str, Any]]:
    """列出可监控的数据库连接（不含密码）。"""
    configs = await DatabaseConnectionService.get_manager_configs(db)
    results: List[Dict[str, Any]] = []
    for item in configs:
        db_type = normalize_monitor_db_type(item["db_type"])
        database = item.get("database") or default_database_for_type(item["db_type"])
        results.append(
            {
                "name": item.get("display_name") or item.get("name") or item["db_name"],
                "db_name": item["db_name"],
                "db_type": db_type,
                "host": item["host"],
                "port": item["port"],
                "database": database,
                "user": item.get("user") or "",
                "has_password": bool(item.get("has_password")),
                "is_system": bool(item.get("is_system")),
            }
        )
    return results


async def resolve_monitor_target(
    db: AsyncSession,
    connection_code: str,
    database: Optional[str] = None,
) -> Dict[str, Any]:
    """解析监控目标完整配置（含密码与 extra_options）。"""
    info = await ConnectionResolver.resolve(connection_code, db)
    target_database = (
        database
        or info.database
        or default_database_for_type(info.db_type)
    )
    return {
        "name": info.display_name or connection_code,
        "db_name": connection_code,
        "db_type": normalize_monitor_db_type(info.db_type),
        "host": info.host,
        "port": info.port,
        "user": info.user,
        "password": info.password,
        "database": target_database,
        "extra_options": info.extra_options or {},
        "is_system": info.is_system,
        "has_password": bool(info.password),
    }


def create_monitor_collector(config: Dict[str, Any]) -> AsyncDatabaseCollector:
    """根据解析后的配置创建采集器。"""
    return AsyncDatabaseCollector(
        db_type=config["db_type"],
        host=config["host"],
        port=config["port"],
        user=config["user"],
        password=config["password"],
        database=config["database"],
        extra_options=config.get("extra_options"),
    )
