#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
回访记录API服务器
提供MySQL数据库的HTTP API接口
"""

import os
import sys
from datetime import datetime
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

try:
    from callback_record_mysql import MySQLCallbackRecordManager, CallbackRecord
    from database_config import DatabaseConfig
    DEPENDENCIES_AVAILABLE = True
except ImportError as e:
    DEPENDENCIES_AVAILABLE = False
    IMPORT_ERROR = str(e)

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 全局数据库管理器
db_manager = None

def initialize_database():
    """初始化数据库连接"""
    global db_manager
    
    if not DEPENDENCIES_AVAILABLE:
        print(f"依赖库未安装: {IMPORT_ERROR}")
        print("请运行: pip install pymysql flask flask-cors")
        return False
    
    try:
        # 加载数据库配置
        config_manager = DatabaseConfig()
        if not config_manager.validate_config():
            print("数据库配置无效，请运行 python database_config.py 进行配置")
            return False
        
        mysql_config = config_manager.get_mysql_config()
        
        # 创建数据库管理器
        db_manager = MySQLCallbackRecordManager(**mysql_config)
        
        # 测试连接
        if db_manager.test_connection():
            print("✓ MySQL数据库连接成功")
            return True
        else:
            print("✗ MySQL数据库连接失败")
            return False
            
    except Exception as e:
        print(f"数据库初始化失败: {e}")
        return False

@app.route('/api/callback-records', methods=['POST'])
def save_callback_record():
    """保存回访记录API"""
    if not db_manager:
        return jsonify({
            'success': False, 
            'message': '数据库未初始化'
        }), 500
    
    try:
        data = request.get_json()
        
        # 验证必需字段
        required_fields = ['caseNumber', 'callbackMethods', 'callbackRecord', 'operator']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({
                    'success': False, 
                    'message': f'缺少必需字段: {field}'
                }), 400
        
        # 创建记录对象
        record = CallbackRecord(
            case_number=data['caseNumber'],
            callback_methods=data['callbackMethods'],
            callback_record=data['callbackRecord'],
            operator=data['operator']
        )
        
        # 保存到数据库
        record_id = db_manager.save_record(record)
        
        return jsonify({
            'success': True,
            'id': record_id,
            'message': '保存成功',
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        print(f"保存回访记录失败: {e}")
        return jsonify({
            'success': False, 
            'message': f'保存失败: {str(e)}'
        }), 500

@app.route('/api/callback-records/<case_number>', methods=['GET'])
def get_callback_records(case_number):
    """获取回访记录API"""
    if not db_manager:
        return jsonify({
            'success': False, 
            'message': '数据库未初始化'
        }), 500
    
    try:
        records = db_manager.get_records_by_case_number(case_number)
        return jsonify({
            'success': True,
            'data': [record.to_dict() for record in records],
            'count': len(records)
        })
        
    except Exception as e:
        print(f"获取回访记录失败: {e}")
        return jsonify({
            'success': False, 
            'message': f'获取失败: {str(e)}'
        }), 500

@app.route('/api/callback-records/statistics', methods=['GET'])
def get_statistics():
    """获取统计信息API"""
    if not db_manager:
        return jsonify({
            'success': False, 
            'message': '数据库未初始化'
        }), 500
    
    try:
        stats = db_manager.get_statistics()
        return jsonify({
            'success': True,
            'data': stats
        })
        
    except Exception as e:
        print(f"获取统计信息失败: {e}")
        return jsonify({
            'success': False, 
            'message': f'获取失败: {str(e)}'
        }), 500

@app.route('/api/callback-records/<int:record_id>', methods=['DELETE'])
def delete_callback_record(record_id):
    """删除回访记录API"""
    if not db_manager:
        return jsonify({
            'success': False, 
            'message': '数据库未初始化'
        }), 500
    
    try:
        success = db_manager.delete_record(record_id)
        if success:
            return jsonify({
                'success': True,
                'message': '删除成功'
            })
        else:
            return jsonify({
                'success': False,
                'message': '记录不存在'
            }), 404
            
    except Exception as e:
        print(f"删除回访记录失败: {e}")
        return jsonify({
            'success': False, 
            'message': f'删除失败: {str(e)}'
        }), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查API"""
    status = {
        'status': 'ok',
        'timestamp': datetime.now().isoformat(),
        'database': 'disconnected'
    }
    
    if db_manager and db_manager.test_connection():
        status['database'] = 'connected'
    
    return jsonify(status)

@app.route('/')
def index():
    """首页 - 显示API文档"""
    return """
    <h1>回访记录API服务器</h1>
    <h2>可用接口：</h2>
    <ul>
        <li><strong>POST</strong> /api/callback-records - 保存回访记录</li>
        <li><strong>GET</strong> /api/callback-records/&lt;case_number&gt; - 获取指定病历号的回访记录</li>
        <li><strong>GET</strong> /api/callback-records/statistics - 获取统计信息</li>
        <li><strong>DELETE</strong> /api/callback-records/&lt;record_id&gt; - 删除回访记录</li>
        <li><strong>GET</strong> /api/health - 健康检查</li>
    </ul>
    
    <h2>使用说明：</h2>
    <ol>
        <li>确保MySQL数据库正在运行</li>
        <li>配置数据库连接信息（运行 python database_config.py）</li>
        <li>启动API服务器（运行 python callback_api_server.py）</li>
        <li>在患者画像页面中使用回访记录功能</li>
    </ol>
    """

# 静态文件服务 - 为患者画像页面提供服务
@app.route('/patient_profiles/<path:filename>')
def patient_profiles(filename):
    """提供患者画像页面文件"""
    return send_from_directory('patient_profiles', filename)

@app.route('/callback_record.js')
def callback_js():
    """提供JavaScript文件"""
    return send_from_directory('.', 'callback_record.js')

def main():
    """主函数"""
    print("=== 回访记录API服务器 ===")
    
    # 检查依赖
    if not DEPENDENCIES_AVAILABLE:
        print(f"错误: {IMPORT_ERROR}")
        print("\n请安装所需依赖:")
        print("pip install pymysql flask flask-cors")
        return
    
    # 初始化数据库
    if not initialize_database():
        print("数据库初始化失败，服务器无法启动")
        print("\n请检查:")
        print("1. MySQL服务是否正在运行")
        print("2. 数据库配置是否正确（运行 python database_config.py 检查）")
        print("3. 数据库用户是否有足够权限")
        return
    
    print("\n服务器启动中...")
    print("API地址: http://localhost:5000/api/")
    print("患者画像: http://localhost:5000/patient_profiles/")
    print("按 Ctrl+C 停止服务器")
    
    try:
        # 启动Flask服务器
        app.run(
            host='0.0.0.0',  # 允许外部访问
            port=5000,
            debug=True,      # 开发模式
            threaded=True    # 多线程支持
        )
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"服务器启动失败: {e}")

if __name__ == "__main__":
    main() 