# -*- coding: utf-8 -*-
"""
submit.py — 问题记录提交路由

从原 server.py 迁入：submit_record。
RECORDS_DIR/PROJECT_ROOT 从 utils.paths 取；record 工具从 utils.record_utils 取；
rebuild_search_index 从 services.record_service 取。
"""

from datetime import datetime

from flask import Blueprint, request, jsonify

from decorators import login_required
from utils.paths import RECORDS_DIR, PROJECT_ROOT
from utils.record_utils import (
    generate_record_id, build_md_filename, build_markdown_content,
)
from services.record_service import rebuild_search_index
from utils.audit import log_audit
from utils.response import error_response
from utils.error_codes import ErrorCodes
from utils.logger import get_logger

logger = get_logger(__name__)

bp = Blueprint('submit', __name__)


@bp.route('/api/submit', methods=['POST'])
@login_required
def submit_record():
    """提交问题记录到知识库"""
    data = request.get_json() or {}

    # 接收字段
    project_name = data.get('project_name', '').strip()
    system_type = data.get('system_type', '').strip()
    apk_product = data.get('apk_product', '').strip()
    phenomenon = data.get('phenomenon', '').strip()
    troubleshoot_steps = data.get('troubleshoot_steps', '').strip()
    root_cause = data.get('root_cause', '').strip()
    solution = data.get('solution', '').strip()
    recorder = data.get('recorder', '').strip()

    # 必填校验
    if not project_name:
        return jsonify(error_response(ErrorCodes.INVALID_PARAM, '项目名称不能为空')), 400
    if not phenomenon:
        return jsonify(error_response(ErrorCodes.INVALID_PARAM, '问题描述不能为空')), 400
    if not recorder:
        return jsonify(error_response(ErrorCodes.INVALID_PARAM, '记录人不能为空')), 400

    try:
        # 1. 生成 Markdown 文件
        record_id = generate_record_id()
        md_content = build_markdown_content(
            record_id=record_id,
            project_name=project_name,
            system_type=system_type,
            apk_product=apk_product,
            phenomenon=phenomenon,
            troubleshoot_steps=troubleshoot_steps,
            root_cause=root_cause,
            solution=solution,
            recorder=recorder,
        )
        md_filename = build_md_filename(record_id, project_name, phenomenon)
        md_filepath = RECORDS_DIR / "项目" / md_filename

        # 确保目录存在
        md_filepath.parent.mkdir(parents=True, exist_ok=True)

        # 写入文件
        md_filepath.write_text(md_content, encoding='utf-8')

        # 2. 重建搜索索引
        rebuild_search_index()

        # 3. 审计日志
        log_audit({
            'timestamp': datetime.now().isoformat(),
            'action': 'submit_record',
            'record_id': record_id,
            'project': project_name,
            'recorder': recorder,
        })

        return jsonify({
            'success': True,
            'message': '问题记录已提交到知识库',
            'record_id': record_id,
            'file': str(md_filepath.relative_to(PROJECT_ROOT)),
        })

    except Exception as e:
        logger.exception("问题入库接口异常")
        return jsonify(error_response(ErrorCodes.RECORD_SUBMIT_ERROR, f'提交失败：{str(e)}')), 500
