#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：security_erp.py
模块描述：安全测试 ERP 配置 API 路由，提供获取/更新 ERP 连接配置接口
          复用功能测试报告的 erp_configs 表与环境变量配置，共用同一套 ERP 配置

作者：czj
创建日期：2026-08-13
最后修改：2026-08-13
"""

import logging

from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.config import settings
from app.models.erp_config import ErpConfig
from app.schemas.security_erp import (
    SecurityErpConfigResponse,
    SecurityErpConfigUpdateRequest,
)

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/erp-config", response_model=SecurityErpConfigResponse, summary="获取安全测试ERP配置")
async def get_erp_config(db: AsyncSession = Depends(get_db)):
    """
    获取安全测试 ERP 配置

    优先从数据库读取，若数据库无记录则回退到环境变量默认值。

    Returns:
        SecurityErpConfigResponse: 当前 ERP 配置
    """
    result = await db.execute(select(ErpConfig).where(ErpConfig.id == 1))
    config = result.scalar_one_or_none()

    if config:
        # 数据库有记录，但空字段回退到环境变量默认值（保证配置自动填充）
        return SecurityErpConfigResponse(
            api_key=config.api_key or settings.ERP_API_KEY or "",
            base_url=config.base_url or settings.ERP_BASE_URL or "",
            developtesting_id=config.developtesting_id or settings.ERP_DEVELOPTESTING_ID or 0,
            type_id=config.type_id or settings.ERP_TYPE_ID or 2,
            image_url_prefix=config.image_url_prefix or settings.ERP_IMAGE_URL_PREFIX or "",
        )

    # 数据库无记录，回退到环境变量
    return SecurityErpConfigResponse(
        api_key=settings.ERP_API_KEY or "",
        base_url=settings.ERP_BASE_URL or "",
        developtesting_id=settings.ERP_DEVELOPTESTING_ID or 0,
        type_id=settings.ERP_TYPE_ID or 2,
        image_url_prefix=settings.ERP_IMAGE_URL_PREFIX or "",
    )


@router.put("/erp-config", response_model=SecurityErpConfigResponse, summary="更新安全测试ERP配置")
async def update_erp_config(request: SecurityErpConfigUpdateRequest, db: AsyncSession = Depends(get_db)):
    """
    更新安全测试 ERP 配置（持久化到数据库）

    更新后的配置会持久化到数据库，服务重启后依然有效，
    与功能测试报告模块共享同一套 ERP 配置。

    Args:
        request: 更新请求（字段可为空，仅更新传入字段）

    Returns:
        SecurityErpConfigResponse: 更新后的配置
    """
    result = await db.execute(select(ErpConfig).where(ErpConfig.id == 1))
    config = result.scalar_one_or_none()

    if not config:
        # 新记录：先用环境变量默认值填充，再用请求值覆盖
        config = ErpConfig(
            id=1,
            api_key=settings.ERP_API_KEY or "",
            base_url=settings.ERP_BASE_URL or "",
            developtesting_id=settings.ERP_DEVELOPTESTING_ID or 0,
            type_id=settings.ERP_TYPE_ID or 2,
            image_url_prefix=settings.ERP_IMAGE_URL_PREFIX or "",
        )
        db.add(config)

    # 更新字段（同时同步运行时环境变量，保证本次进程内立即生效）
    if request.api_key is not None:
        config.api_key = request.api_key
        settings.ERP_API_KEY = request.api_key
    if request.base_url is not None:
        config.base_url = request.base_url
        settings.ERP_BASE_URL = request.base_url
    if request.developtesting_id is not None:
        config.developtesting_id = request.developtesting_id
        settings.ERP_DEVELOPTESTING_ID = request.developtesting_id
    if request.type_id is not None:
        config.type_id = request.type_id
        settings.ERP_TYPE_ID = request.type_id
    if request.image_url_prefix is not None:
        config.image_url_prefix = request.image_url_prefix
        settings.ERP_IMAGE_URL_PREFIX = request.image_url_prefix

    await db.commit()
    await db.refresh(config)

    logger.info("安全测试ERP配置已更新（持久化到数据库，与功能测试报告共享）")

    return SecurityErpConfigResponse(
        api_key=config.api_key or settings.ERP_API_KEY or "",
        base_url=config.base_url or settings.ERP_BASE_URL or "",
        developtesting_id=config.developtesting_id or settings.ERP_DEVELOPTESTING_ID or 0,
        type_id=config.type_id or settings.ERP_TYPE_ID or 2,
        image_url_prefix=config.image_url_prefix or settings.ERP_IMAGE_URL_PREFIX or "",
    )