"""Backend API client helpers."""

import json
import logging
from typing import Any, Dict, List, Optional

import httpx

try:
    from .env_config import get_backend_base_url
except ImportError:
    from env_config import get_backend_base_url


logger = logging.getLogger(__name__)


class DataSourceAPIClient:
    """HTTP client for backend datasource APIs."""

    def __init__(
        self,
        base_url: Optional[str] = None,
        token: Optional[str] = None
    ):
        if base_url is None:
            base_url = get_backend_base_url()

        self.base_url = base_url.rstrip("/")
        self.token = token or (
            "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjJiYTk4ODllLWM2ZGItNDQ5YS1i"
            "ZmFjLTQ2YzMxODFlODg5NCJ9.dvi8zm0LsWvJ_h9zD5blnHFRxa4z4_WBm1R487ekE7HlHzrN6dn"
            "vqhK8askqT5b1EcE8myHwRzLVMoI8UOjOrw"
        )
        self.client = httpx.Client(timeout=30.0)

    def _get_headers(self) -> Dict[str, str]:
        return {
            "Authorization": f"Bearer {self.token}",
        }

    def get_skill_by_id(self, skill_id: str) -> Dict[str, Any]:
        """Fetch skill details by skill id."""
        try:
            url = f"{self.base_url}/datasource/skill/getBySkillId/{skill_id}"

            logger.info(f"正在调用 API: {url}")
            logger.debug(f"请求参数 - skill_id: {skill_id}")

            response = self.client.get(url, headers=self._get_headers())
            response.raise_for_status()
            data = response.json()

            logger.info(f"API 调用成功: {url}")
            logger.debug(f"响应数据: {data}")
            return data

        except httpx.TimeoutException:
            error_msg = f"API 请求超时: {url}"
            logger.error(error_msg)
            raise Exception(error_msg)
        except httpx.HTTPStatusError as e:
            error_msg = f"API 请求失败 (HTTP {e.response.status_code}): {url}"
            logger.error(error_msg)
            logger.error(f"错误响应: {e.response.text}")
            raise Exception(error_msg)
        except httpx.RequestError as e:
            error_msg = f"API 请求异常: {url}, 错误: {str(e)}"
            logger.error(error_msg)
            raise Exception(error_msg)
        except Exception as e:
            error_msg = f"处理 API 响应时出错: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise Exception(error_msg)

    def test_sql_with_schema(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """Call backend SQL test endpoint."""
        try:
            logger.info("=" * 80)
            logger.info("test_sql_with_schema 接口接收到的数据:")
            logger.info(f"数据类型: {type(request_data)}")
            logger.info(f"数据内容: {json.dumps(request_data, ensure_ascii=False, indent=2)}")
            logger.info(f"数据源 ID: {request_data.get('datasourceId')}")
            logger.info(f"业务名称: {request_data.get('businessName')}")
            logger.info(f"业务描述: {request_data.get('businessDescription')}")
            logger.info(f"SQL 模板: {request_data.get('sqlTemplate')}")
            logger.info(f"参数定义: {request_data.get('parameters')}")
            logger.info(f"测试参数: {request_data.get('testParams')}")
            if "userId" in request_data:
                logger.info(f"用户 ID: {request_data.get('userId')}")
            logger.info("=" * 80)

            url = f"{self.base_url}/datasource/sqlExecutionLog/testSqlWithSchema"
            headers = self._get_headers()
            headers["Content-Type"] = "application/json"
            headers["Accept"] = "*/*"

            logger.info(f"正在调用测试 SQL API: {url}")
            logger.debug(f"请求数据: {json.dumps(request_data, ensure_ascii=False, indent=2)}")

            response = self.client.post(url, headers=headers, json=request_data)
            response.raise_for_status()
            data = response.json()

            logger.info("=" * 80)
            logger.info("test_sql_with_schema 接口返回的数据:")
            logger.info(f"HTTP 状态码: {response.status_code}")
            logger.info(f"响应数据类型: {type(data)}")
            logger.info(f"响应数据内容: {json.dumps(data, ensure_ascii=False, indent=2)}")
            if isinstance(data, dict):
                logger.info(f"响应 code: {data.get('code')}")
                logger.info(f"响应 msg: {data.get('msg')}")
                logger.info(f"响应 data: {data.get('data')}")
            logger.info("=" * 80)

            logger.info("测试 SQL API 调用成功")
            return data

        except httpx.TimeoutException:
            error_msg = f"测试 SQL API 请求超时: {url}"
            logger.error(error_msg)
            raise Exception(error_msg)
        except httpx.HTTPStatusError as e:
            error_msg = f"测试 SQL API 请求失败 (HTTP {e.response.status_code}): {url}"
            logger.error(error_msg)
            logger.error(f"错误响应: {e.response.text}")
            raise Exception(error_msg)
        except httpx.RequestError as e:
            error_msg = f"测试 SQL API 请求异常: {url}, 错误: {str(e)}"
            logger.error(error_msg)
            raise Exception(error_msg)
        except Exception as e:
            error_msg = f"处理测试 SQL API 响应时出错: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise Exception(error_msg)

    def close(self):
        """Close the underlying HTTP client."""
        self.client.close()


default_client = DataSourceAPIClient()


def get_skill_by_id(
    skill_id: str,
    base_url: Optional[str] = None,
    token: Optional[str] = None
) -> Dict[str, Any]:
    """Convenience wrapper for skill lookup."""
    if base_url or token:
        client = DataSourceAPIClient(base_url=base_url, token=token)
        return client.get_skill_by_id(skill_id)
    return default_client.get_skill_by_id(skill_id)


def test_sql_with_schema(
    request_data: Dict[str, Any],
    base_url: Optional[str] = None,
    token: Optional[str] = None
) -> Dict[str, Any]:
    """Convenience wrapper for SQL test endpoint."""
    if base_url or token:
        client = DataSourceAPIClient(base_url=base_url, token=token)
        return client.test_sql_with_schema(request_data)
    return default_client.test_sql_with_schema(request_data)


def process_skill_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Map backend skill response into business query configs."""
    try:
        data_list = response.get("data", [])
        queries = []

        for skill in data_list:
            sql_params_raw = skill.get("sqlParams")
            sql_params: Dict[str, Any] = {}

            if isinstance(sql_params_raw, dict):
                sql_params = sql_params_raw
            elif isinstance(sql_params_raw, str) and sql_params_raw.strip():
                try:
                    parsed_sql_params = json.loads(sql_params_raw)
                    if isinstance(parsed_sql_params, dict):
                        sql_params = parsed_sql_params
                    else:
                        logger.warning(
                            f"技能 {skill.get('name')} (ID: {skill.get('id')}) 的 sqlParams 不是对象，已回退为空对象"
                        )
                except json.JSONDecodeError:
                    logger.warning(
                        f"技能 {skill.get('name')} (ID: {skill.get('id')}) 的 sqlParams 不是合法 JSON，已回退为空对象"
                    )

            query = {
                "id": skill.get("id"),
                "businessName": skill.get("name"),
                "businessDescription": skill.get("description"),
                "sqlTemplate": skill.get("sqlTemplate"),
                "parameters": sql_params,
                "datasourceId": skill.get("datasourceId"),
            }
            queries.append(query)

        logger.info(f"成功处理 {len(queries)} 条技能数据")
        return queries
    except Exception as e:
        logger.error(f"处理 API 响应数据失败: {e}", exc_info=True)
        raise
