# 录音管理蓝图 - 下载相关路由
# 处理转录稿、摘要、聊天对话、笔记的 Word 文档下载

from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from datetime import datetime, timedelta
import json
import re

from src.clients import db
from src.models import Recording, TranscriptTemplate
from src.services import (
    add_unicode_paragraph,
    create_docx_with_unicode_title,
    save_and_send_docx,
    process_markdown_to_docx,
    get_recording_display_title,
    build_docx_download_filename,
)

recording_download_bp = Blueprint('recording_download', __name__)


@recording_download_bp.route('/recording/<int:recording_id>/download/transcript')
@login_required
def download_transcript_with_template(recording_id):
    """下载转录稿(使用自定义模板格式)为 Word 文档"""
    recording = db.session.get(Recording, recording_id)
    if not recording:
        return jsonify({'error': '录音未找到'}), 404

    if recording.user_id and recording.user_id != current_user.id:
        return jsonify({'error': '您没有权限访问此录音'}), 403

    if not recording.transcription:
        return jsonify({'error': '此录音没有可用的转录内容'}), 400

    # 从查询参数获取模板 ID
    template_id = request.args.get('template_id')
    
    use_template = True
    template = None
    if template_id == 'none':
        use_template = False
    elif template_id:
        try:
            template_id = int(template_id)
            template = TranscriptTemplate.query.filter_by(
                id=template_id,
                user_id=current_user.id
            ).first()
        except (ValueError, TypeError):
            pass
            
    if use_template and not template:
        template = TranscriptTemplate.query.filter_by(
            user_id=current_user.id,
            is_default=True
        ).first()

    if not template or not use_template:
        template_format = "[{{speaker}}]: {{text}}"
    else:
        template_format = template.template

    def format_time(seconds):
        if seconds is None:
            return "00:00:00"
        td = timedelta(seconds=seconds)
        hours = int(td.total_seconds() // 3600)
        minutes = int((td.total_seconds() % 3600) // 60)
        secs = int(td.total_seconds() % 60)
        return f"{hours:02d}:{minutes:02d}:{secs:02d}"

    def format_srt_time(seconds):
        if seconds is None:
            return "00:00:00,000"
        td = timedelta(seconds=seconds)
        hours = int(td.total_seconds() // 3600)
        minutes = int((td.total_seconds() % 3600) // 60)
        secs = int(td.total_seconds() % 60)
        millis = int((td.total_seconds() % 1) * 1000)
        return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"

    try:
        transcription_data = json.loads(recording.transcription)
    except (json.JSONDecodeError, TypeError):
        transcription_data = [{'speaker': '说话人', 'sentence': recording.transcription}]

    from docx import Document
    doc = Document()
    
    title_text = f'转录稿:{get_recording_display_title(recording)}'
    create_docx_with_unicode_title(doc, title_text)

    template_label = template.name if template else '原文'

    add_unicode_paragraph(doc, f'录音时间:{recording.created_at.strftime("%Y-%m-%d %H:%M")}')
    add_unicode_paragraph(doc, f'导出模板:{template_label}')
    doc.add_paragraph('')

    if type(transcription_data) is list:
        for index, segment in enumerate(transcription_data, 1):
            line = template_format
            replacements = {
                '{{index}}': str(index),
                '{{speaker}}': segment.get('speaker', '未知说话人'),
                '{{text}}': segment.get('sentence', ''),
                '{{start_time}}': format_time(segment.get('start_time')),
                '{{end_time}}': format_time(segment.get('end_time')),
            }
            for key, value in replacements.items():
                line = line.replace(key, value)
            line = re.sub(r'{{(.*?)\|upper}}', lambda m: replacements.get('{{' + m.group(1) + '}}', '').upper(), line)
            line = re.sub(r'{{start_time\|srt}}', format_srt_time(segment.get('start_time')), line)
            line = re.sub(r'{{end_time\|srt}}', format_srt_time(segment.get('end_time')), line)
            add_unicode_paragraph(doc, line)
    else:
        add_unicode_paragraph(doc, str(transcription_data))

    filename = build_docx_download_filename('转录稿', recording, recording_id, [template_label])
    return save_and_send_docx(doc, filename, f'transcript_{recording_id}.docx')


@recording_download_bp.route('/recording/<int:recording_id>/download/summary')
@login_required
def download_summary_word(recording_id):
    """下载录音摘要为 Word 文档"""
    recording = db.session.get(Recording, recording_id)
    if not recording:
        return jsonify({'error': '录音未找到'}), 404
        
    if recording.user_id and recording.user_id != current_user.id:
        return jsonify({'error': '您没有权限访问此录音'}), 403
        
    if not recording.summary:
        return jsonify({'error': '此录音没有可用的摘要'}), 400
    
    from docx import Document
    doc = Document()
    
    title_text = f'会议摘要:{get_recording_display_title(recording)}'
    create_docx_with_unicode_title(doc, title_text)

    add_unicode_paragraph(doc, f'上传时间:{recording.created_at.strftime("%Y-%m-%d %H:%M")}')
    if recording.meeting_date:
        add_unicode_paragraph(doc, f'会议日期:{recording.meeting_date.strftime("%Y-%m-%d")}')
    if recording.participants:
        add_unicode_paragraph(doc, f'参会人员:{recording.participants}')
    if recording.tags:
        tags_str = ', '.join([tag.name for tag in recording.tags])
        add_unicode_paragraph(doc, f'标签:{tags_str}')
    doc.add_paragraph('')

    process_markdown_to_docx(doc, recording.summary)
    
    filename = build_docx_download_filename('会议摘要', recording, recording_id)
    return save_and_send_docx(doc, filename, f'summary_{recording_id}.docx')


@recording_download_bp.route('/recording/<int:recording_id>/download/chat', methods=['POST'])
@login_required
def download_chat_word(recording_id):
    """下载聊天对话为 Word 文档"""
    recording = db.session.get(Recording, recording_id)
    if not recording:
        return jsonify({'error': '录音未找到'}), 404
        
    if recording.user_id and recording.user_id != current_user.id:
        return jsonify({'error': '您没有权限访问此录音'}), 403
    
    data = request.json
    if not data or 'messages' not in data:
        return jsonify({'error': '未提供消息'}), 400
    
    messages = data['messages']
    if not messages:
        return jsonify({'error': '没有可下载的消息'}), 400
    
    from docx import Document
    doc = Document()
    
    title_text = f'对话记录:{get_recording_display_title(recording)}'
    create_docx_with_unicode_title(doc, title_text)

    add_unicode_paragraph(doc, f'录音时间:{recording.created_at.strftime("%Y-%m-%d %H:%M")}')
    add_unicode_paragraph(doc, f'导出时间:{datetime.utcnow().strftime("%Y-%m-%d %H:%M")}')
    doc.add_paragraph('')
    
    for message in messages:
        role = message.get('role', 'unknown')
        content = message.get('content', '')
        thinking = message.get('thinking', '')
        
        if role == 'user':
            p = doc.add_paragraph()
            run = p.add_run('你:')
            run.bold = True
        elif role == 'assistant':
            p = doc.add_paragraph()
            run = p.add_run('智能助手:')
            run.bold = True
        else:
            p = doc.add_paragraph()
            run = p.add_run(f'{role.title()}:')
            run.bold = True
        
        if thinking and role == 'assistant':
            p = doc.add_paragraph()
            p.add_run('[模型思考]\n').italic = True
            p.add_run(thinking).italic = True
            doc.add_paragraph('')
        
        process_markdown_to_docx(doc, content)
        doc.add_paragraph('')
    
    filename = build_docx_download_filename('对话记录', recording, recording_id)
    return save_and_send_docx(doc, filename, f'chat_{recording_id}.docx')


@recording_download_bp.route('/recording/<int:recording_id>/download/notes')
@login_required
def download_notes_word(recording_id):
    """下载录音笔记为 Word 文档"""
    recording = db.session.get(Recording, recording_id)
    if not recording:
        return jsonify({'error': '录音未找到'}), 404
        
    if recording.user_id and recording.user_id != current_user.id:
        return jsonify({'error': '您没有权限访问此录音'}), 403
        
    if not recording.notes:
        return jsonify({'error': '此录音没有可用的笔记'}), 400
    
    from docx import Document
    doc = Document()
    
    title_text = f'会议笔记:{get_recording_display_title(recording)}'
    create_docx_with_unicode_title(doc, title_text)

    add_unicode_paragraph(doc, f'上传时间:{recording.created_at.strftime("%Y-%m-%d %H:%M")}')
    if recording.meeting_date:
        add_unicode_paragraph(doc, f'会议日期:{recording.meeting_date.strftime("%Y-%m-%d")}')
    if recording.participants:
        add_unicode_paragraph(doc, f'参会人员:{recording.participants}')
    if recording.tags:
        tags_str = ', '.join([tag.name for tag in recording.tags])
        add_unicode_paragraph(doc, f'标签:{tags_str}')
    doc.add_paragraph('')

    process_markdown_to_docx(doc, recording.notes)
    
    filename = build_docx_download_filename('会议笔记', recording, recording_id)
    return save_and_send_docx(doc, filename, f'notes_{recording_id}.docx')
