#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
创建默认安全测试配置（直接操作数据库，避免 HTTP 编码问题）
"""
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.models.security_config import SecurityConfig


def main():
    db_path = os.path.join(os.path.dirname(__file__), "..", "data", "test_platform.db")
    db_url = f"sqlite:///{os.path.abspath(db_path)}"

    engine = create_engine(db_url)
    Session = sessionmaker(bind=engine)
    session = Session()

    try:
        # 检查是否已存在默认配置
        existing = session.query(SecurityConfig).filter(SecurityConfig.is_default == True).first()
        if existing:
            print(f"默认配置已存在: {existing.name} ({existing.id})")
            return

        config = SecurityConfig(
            id="sec_cfg_default",
            name="新统一平台安全测试配置",
            target_url="https://192.168.5.44",
            server_ip="192.168.5.44",
            verify_ssl=False,
            timeout=30,
            accounts={
                "superadmin": {"username": "superadmin", "password": "Ubains@1357"},
                "admin": {"username": "admin@aq", "password": "Ubains@1357"},
                "user": {"username": "user@aq", "password": "Ubains@1357"},
                "captcha": "csba",
            },
            auth_config={
                "token_type": "accessToken",
                "mechanism": "JWT",
                "login_path": "/platform/api/auth/login",
                "token_header": "accessToken",
                "captcha_path": "/platform/api/code",
            },
            rate_limits={
                "brute_force_max": 20,
                "rate_limit_max": 100,
                "request_interval": 0.5,
            },
            api_prefixes={
                "meeting": "/api/",
                "monitor": "/monitor/api2/api/",
                "platform": "/platform/api/",
            },
            is_default=True,
            description="默认安全测试配置，用于新统一平台（192.168.5.44）",
        )

        session.add(config)
        session.commit()
        print(f"✅ 默认配置创建成功: {config.id}")
        print(f"   名称: {config.name}")
        print(f"   目标: {config.target_url}")

    except Exception as e:
        session.rollback()
        print(f"❌ 错误: {e}")
    finally:
        session.close()


if __name__ == "__main__":
    main()
