#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
数据源导入/导出
"""
import logging
from typing import Any, Dict

from sqlalchemy.ext.asyncio import AsyncSession

from core.data_source.model import DataSource
from core.data_source.service import DataSourceService

logger = logging.getLogger(__name__)

EXPORT_FIELD_KEYS = [
    "name", "code", "source_type", "description", "status",
    "api_url", "api_method", "api_headers", "api_query_params", "api_body_type",
    "api_body", "api_content_type", "api_timeout", "api_data_path",
    "api_auth_type", "api_auth_config", "api_retry_count", "api_retry_interval",
    "api_success_condition", "api_proxy", "api_follow_redirects", "api_verify_ssl",
    "sql_content", "db_connection", "static_data", "params",
    "result_type", "tree_config", "field_mapping", "chart_config",
    "cache_enabled", "cache_ttl",
]


class DataSourceImportExportException(Exception):
    """数据源导入导出异常"""
    pass


def _source_to_export_dict(source: DataSource) -> Dict[str, Any]:
    """将数据源转为可导出配置（不含 id、统计字段）"""
    return {
        "name": source.name,
        "code": source.code,
        "source_type": source.source_type or "static",
        "description": source.description or "",
        "status": source.status if source.status is not None else True,
        "api_url": source.api_url or "",
        "api_method": source.api_method or "GET",
        "api_headers": source.api_headers or {},
        "api_query_params": source.api_query_params or [],
        "api_body_type": source.api_body_type or "none",
        "api_body": source.api_body or {},
        "api_content_type": source.api_content_type or "",
        "api_timeout": source.api_timeout or 30,
        "api_data_path": source.api_data_path or "",
        "api_auth_type": source.api_auth_type or "none",
        "api_auth_config": source.api_auth_config or {},
        "api_retry_count": source.api_retry_count or 0,
        "api_retry_interval": source.api_retry_interval or 1,
        "api_success_condition": source.api_success_condition or {},
        "api_proxy": source.api_proxy or "",
        "api_follow_redirects": (
            source.api_follow_redirects if source.api_follow_redirects is not None else True
        ),
        "api_verify_ssl": (
            source.api_verify_ssl if source.api_verify_ssl is not None else True
        ),
        "sql_content": source.sql_content or "",
        "db_connection": source.db_connection or "default",
        "static_data": source.static_data or [],
        "params": source.params or [],
        "result_type": source.result_type or "list",
        "tree_config": source.tree_config or {},
        "field_mapping": source.field_mapping or {},
        "chart_config": source.chart_config or {},
        "cache_enabled": source.cache_enabled or False,
        "cache_ttl": source.cache_ttl or 300,
    }


def _build_import_payload(data: Dict[str, Any]) -> Dict[str, Any]:
    """从导入 JSON 构建创建参数"""
    defaults = {
        "source_type": "static",
        "description": "",
        "status": True,
        "api_url": "",
        "api_method": "GET",
        "api_headers": {},
        "api_query_params": [],
        "api_body_type": "none",
        "api_body": {},
        "api_content_type": "",
        "api_timeout": 30,
        "api_data_path": "",
        "api_auth_type": "none",
        "api_auth_config": {},
        "api_retry_count": 0,
        "api_retry_interval": 1,
        "api_success_condition": {},
        "api_proxy": "",
        "api_follow_redirects": True,
        "api_verify_ssl": True,
        "sql_content": "",
        "db_connection": "default",
        "static_data": [],
        "params": [],
        "result_type": "list",
        "tree_config": {},
        "field_mapping": {},
        "chart_config": {},
        "cache_enabled": False,
        "cache_ttl": 300,
    }
    payload = {**defaults}
    for key in EXPORT_FIELD_KEYS:
        if key in data and data[key] is not None:
            payload[key] = data[key]
    payload["application_id"] = data.get("application_id")
    return payload


async def export_config(db: AsyncSession, source_id: str) -> Dict[str, Any]:
    """导出数据源配置"""
    source = await DataSourceService.get_by_id(db, source_id)
    if not source:
        raise DataSourceImportExportException("数据源不存在")
    return _source_to_export_dict(source)


async def check_import(db: AsyncSession, code: str) -> Dict[str, Any]:
    """导入预检查：编码是否冲突"""
    code_exists = False
    if code:
        code_exists = await DataSourceService.check_code_exists(db, code)
    return {
        "code_exists": code_exists,
        "can_import": not code_exists,
    }


async def import_config(db: AsyncSession, data: Dict[str, Any]) -> DataSource:
    """导入数据源配置"""
    if not data.get("name"):
        raise DataSourceImportExportException("缺少必要字段: name")
    if not data.get("code"):
        raise DataSourceImportExportException("缺少必要字段: code")

    if await DataSourceService.check_code_exists(db, data["code"]):
        raise DataSourceImportExportException(f"数据源编码已存在: {data['code']}")

    create_data = _build_import_payload(data)
    source = await DataSourceService.create(db, create_data)
    logger.info("数据源导入成功: %s", source.code)
    return source
