# -*- coding: utf-8 -*-
"""
server.py — 问题排查助手 Web 服务

功能：
  提供 Web API 接口：
    - POST /api/troubleshoot — 接收问题描述，返回排查指引
    - POST /api/submit        — 接收问题记录提交，写入问题库

启动：
  python server.py

访问：
  http://localhost:8088
"""

import os
import re
import sys
import json
import time
import uuid
import traceback
from pathlib import Path
from datetime import datetime

from flask import Flask, request, jsonify, render_template, send_from_directory, send_file, session, redirect, url_for
from io import BytesIO

# ============================================================
# 认证模块导入
# ============================================================
from auth import user_manager
from decorators import login_required, admin_required, page_login_required

# ============================================================
# 日志与统一响应工具
# ============================================================
from utils.logger import get_logger
from utils.error_codes import ErrorCodes
from utils.response import error_response, success_response

logger = get_logger(__name__)

# ============================================================
# 配置
# ============================================================

# 路径常量集中管理（utils/paths.py）—— P1-3 步骤1 抽取
from utils.paths import (
    SCRIPT_DIR, DATA_DIR, PROJECT_ROOT, RECORDS_DIR, CONFIG_FILE, AUDIT_LOG_FILE,
)

# ============================================================
# 初始化
# ============================================================

# 强制 UTF-8 编码
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')


def create_app():
    """Flask 应用工厂 — 创建并配置 app，注册所有 Blueprint。

    模块级 `app = create_app()` 保持 `server.app` 引用向后兼容；
    工厂模式便于未来测试 fixture 与多实例部署。
    """
    app = Flask(
        __name__,
        template_folder=str(SCRIPT_DIR / "templates"),
        static_folder=str(SCRIPT_DIR / "static"),
    )

    # Session 配置
    app.secret_key = os.environ.get('SECRET_KEY')
    if not app.secret_key:
        import secrets
        app.secret_key = secrets.token_hex(32)
        print("[警告] SECRET_KEY 环境变量未设置，已生成随机密钥")
        print("[提示] 生产环境请设置 SECRET_KEY 环境变量")
    app.config['SESSION_TYPE'] = 'filesystem'
    app.config['PERMANENT_SESSION_LIFETIME'] = 86400  # 24小时

    # 注册 Blueprint（url_prefix 留空，保持 API 路径不变）
    from routes.platform import bp as platform_bp
    from routes.auth import bp as auth_bp
    from routes.troubleshoot import bp as troubleshoot_bp
    from routes.service_manage import bp as service_manage_bp
    from service_monitor import bp as service_monitor_bp
    from routes.cache import bp as cache_bp
    from routes.export import bp as export_bp
    from routes.submit import bp as submit_bp
    app.register_blueprint(platform_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(troubleshoot_bp)
    app.register_blueprint(service_manage_bp)
    app.register_blueprint(service_monitor_bp)
    app.register_blueprint(cache_bp)
    app.register_blueprint(export_bp)
    app.register_blueprint(submit_bp)

    return app


# 模块级 app（启动即创建，保持 server.app 向后兼容）
app = create_app()

# 加载配置
# ============================================================
# 配置与单例（已迁至 container.py —— P1-3 步骤2）
# ============================================================

from container import (
    load_config, get_config, get_search_engine, reset_search_engine,
    get_safety_filter, get_cache_manager, get_skill_md,
)

# 模块级 config（启动即加载，保持原行为）
config = get_config()

# ============================================================
# Prompt 构建与 Claude API 调用（已迁至 services/ai_service.py —— P1-3 步骤4）
# ============================================================

from services.ai_service import (
    build_prompt, call_claude_api, call_claude_api_stream,
    generate_mock_response, split_mock_response,
)


# ============================================================
# 启动
# ============================================================

if __name__ == '__main__':
    print("="*50)
    print("🔍 问题排查助手 Web 服务")
    print("="*50)
    print(f"📁 项目根目录：{PROJECT_ROOT}")
    print(f"📊 知识库：{len(get_search_engine().records)} 条记录")
    print(f"🌐 服务地址：http://localhost:8088")
    print("="*50)

    # debug 从环境变量读取（默认开发环境开启，生产用 FLASK_DEBUG=0 关闭）
    debug = os.environ.get('FLASK_DEBUG', '1') == '1'

    app.run(
        host='0.0.0.0',
        port=8088,
        debug=debug,
        threaded=True,
    )