# 分享蓝图
# 处理分享链接的创建、查看和管理

import os
from flask import Blueprint, render_template, request, jsonify, send_file, url_for, current_app
from flask_login import login_required, current_user
from src.clients import db
from src.models import Share, Recording
from src.utils.markdown import md_to_html

# 创建分享蓝图
share_bp = Blueprint('share', __name__)

# 全局变量
csrf = None

def init_share_bp(csrf_instance):
    """初始化蓝图所需的全局变量"""
    global csrf
    csrf = csrf_instance


@share_bp.route('/share/<string:public_id>', methods=['GET'])
def view_shared_recording(public_id):
    """查看分享的录音"""
    share = Share.query.filter_by(public_id=public_id).first_or_404()
    recording = share.recording
    
    # 为公共视图创建有限的字典
    recording_data = {
        'id': recording.id,
        'public_id': share.public_id,
        'title': recording.title,
        'participants': recording.participants,
        'transcription': recording.transcription,
        'summary': md_to_html(recording.summary) if share.share_summary else None,
        'notes': md_to_html(recording.notes) if share.share_notes else None,
        'meeting_date': f"{recording.meeting_date.isoformat()}T00:00:00" if recording.meeting_date else None,
        'mime_type': recording.mime_type
    }
    
    return render_template('share.html', recording=recording_data)


@share_bp.route('/api/recording/<int:recording_id>/share', methods=['GET'])
@login_required
def get_existing_share(recording_id):
    """检查录音是否已存在分享链接"""
    recording = db.session.get(Recording, recording_id)
    if not recording or recording.user_id != current_user.id:
        return jsonify({'error': '录音未找到或您没有权限查看'}), 404
    
    existing_share = Share.query.filter_by(
        recording_id=recording.id,
        user_id=current_user.id
    ).order_by(Share.created_at.desc()).first()
    
    if existing_share:
        relative_path = url_for('share.view_shared_recording', public_id=existing_share.public_id)
        # 获取纯主机名 (去掉 request.host 可能自带的端口)
        config_port = os.environ.get('EXTERNAL_PORT', '8083')
        hostname = request.host.split(':')[0]
        # 拼接完整链接
        share_url = f"{request.scheme}://{hostname}:{config_port}/tool/speakr{relative_path}"
        return jsonify({
            'success': True,
            'exists': True,
            'share_url': share_url,
            'share': existing_share.to_dict()
        }), 200
    else:
        return jsonify({
            'success': True,
            'exists': False
        }), 200


@share_bp.route('/api/recording/<int:recording_id>/share', methods=['POST'])
@login_required
def create_share(recording_id):
    """创建新的分享链接"""
    if not request.is_secure:
        return jsonify({'error': '分享功能仅在安全连接 (HTTPS) 下可用'}), 403
        
    recording = db.session.get(Recording, recording_id)
    if not recording or recording.user_id != current_user.id:
        return jsonify({'error': '录音未找到或您没有权限分享'}), 404
        
    data = request.json
    share_summary = data.get('share_summary', True)
    share_notes = data.get('share_notes', True)
    force_new = data.get('force_new', False)
    
    # 检查此录音是否已存在任何分享
    # 如果有多个，获取最近的一个
    existing_share = Share.query.filter_by(
        recording_id=recording.id,
        user_id=current_user.id
    ).order_by(Share.created_at.desc()).first()
    
    if existing_share and not force_new:
        # 如果分享权限发生变化，更新它们
        if existing_share.share_summary != share_summary or existing_share.share_notes != share_notes:
            existing_share.share_summary = share_summary
            existing_share.share_notes = share_notes
            db.session.commit()
        
        # 返回现有分享信息
        relative_path = url_for('share.view_shared_recording', public_id=existing_share.public_id)
        config_port = os.environ.get('EXTERNAL_PORT', '8083')
        hostname = request.host.split(':')[0]
        # 拼接完整链接
        share_url = f"{request.scheme}://{hostname}:{config_port}/tool/speakr{relative_path}"
        return jsonify({
            'success': True, 
            'share_url': share_url, 
            'share': existing_share.to_dict(),
            'existing': True,
            'message': '使用此录音的现有分享链接'
        }), 200
    
    # 创建新分享（不存在现有分享或 force_new 为 True）
    share = Share(
        recording_id=recording.id,
        user_id=current_user.id,
        share_summary=share_summary,
        share_notes=share_notes
    )
    db.session.add(share)
    db.session.commit()
    
    relative_path = url_for('share.view_shared_recording', public_id=share.public_id)
    config_port = os.environ.get('EXTERNAL_PORT', '8083')
    hostname = request.host.split(':')[0]
    # 拼接完整链接
    share_url = f"{request.scheme}://{hostname}:{config_port}/tool/speakr{relative_path}"
    
    return jsonify({
        'success': True, 
        'share_url': share_url, 
        'share': share.to_dict(),
        'existing': False
    }), 201


@share_bp.route('/api/shares', methods=['GET'])
@login_required
def get_shares():
    """获取当前用户的所有分享"""
    shares = Share.query.filter_by(user_id=current_user.id).order_by(Share.created_at.desc()).all()
    return jsonify([share.to_dict() for share in shares])


@share_bp.route('/api/share/<int:share_id>', methods=['PUT'])
@login_required
def update_share(share_id):
    """更新分享权限"""
    share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()
    data = request.json
    
    if 'share_summary' in data:
        share.share_summary = data['share_summary']
    if 'share_notes' in data:
        share.share_notes = data['share_notes']
        
    db.session.commit()
    return jsonify({'success': True, 'share': share.to_dict()})


@share_bp.route('/api/share/<int:share_id>', methods=['DELETE'])
@login_required
def delete_share(share_id):
    """删除分享"""
    share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()
    db.session.delete(share)
    db.session.commit()
    return jsonify({'success': True})


@share_bp.route('/share/audio/<string:public_id>')
def get_shared_audio(public_id):
    """获取分享的音频文件"""
    try:
        share = Share.query.filter_by(public_id=public_id).first_or_404()
        recording = share.recording
        if not recording or not recording.audio_path:
            return jsonify({'error': '录音或音频文件未找到'}), 404
        if not os.path.exists(recording.audio_path):
            current_app.logger.error(f"音频文件在服务器上缺失：{recording.audio_path}")
            return jsonify({'error': '音频文件在服务器上缺失'}), 404
        return send_file(recording.audio_path)
    except Exception as e:
        current_app.logger.error(f"为 public_id {public_id} 提供分享音频时出错：{e}", exc_info=True)
        return jsonify({'error': '发生意外错误'}), 500
