#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import re
from datetime import timedelta


def parse_time(time_str):
    """Parse SRT time string (HH:MM:SS,mmm) to timedelta."""
    hours, minutes, seconds_ms = time_str.split(":")
    seconds, milliseconds = seconds_ms.split(",")
    return timedelta(
        hours=int(hours),
        minutes=int(minutes),
        seconds=int(seconds),
        milliseconds=int(milliseconds),
    )


def format_time(td):
    """Format timedelta to SRT time string (HH:MM:SS,mmm)."""
    total_ms = int(round(td.total_seconds() * 1000))
    if total_ms < 0:
        total_ms = 0
    hours = total_ms // 3600000
    minutes = (total_ms % 3600000) // 60000
    seconds = (total_ms % 60000) // 1000
    milliseconds = total_ms % 1000
    return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"


def _parse_hms_or_hms_ms(time_str):
    """Parse HH:MM:SS or HH:MM:SS,mmm string into timedelta."""
    if "," in time_str:
        hms, ms = time_str.split(",", 1)
        milliseconds = int(ms)
    else:
        hms = time_str
        milliseconds = 0

    h, m, s = map(int, hms.split(":"))
    return timedelta(hours=h, minutes=m, seconds=s, milliseconds=milliseconds)


def parse_edited_time_range(time_range_str):
    """Parse editedTimeRange to (start_timedelta, end_timedelta)."""
    if not time_range_str:
        return None, None

    parts = time_range_str.split("-")
    if len(parts) != 2:
        return None, None

    start_time_str, end_time_str = parts
    return _parse_hms_or_hms_ms(start_time_str), _parse_hms_or_hms_ms(end_time_str)


def merge_subtitle_files(subtitle_items, output_file=None):
    """Merge subtitle files based on editedTimeRange offsets."""
    sorted_items = sorted(
        subtitle_items,
        key=lambda x: parse_edited_time_range(x.get("editedTimeRange", ""))[0] or timedelta(),
    )

    merged_subtitles = []
    subtitle_index = 1
    valid_items_count = 0

    for item in sorted_items:
        subtitle_path = item.get("subtitle")
        if not subtitle_path or not os.path.exists(subtitle_path):
            print(f"跳过项目 {item.get('_id')}：字幕文件不存在或路径为空")
            continue

        offset_time, _ = parse_edited_time_range(item.get("editedTimeRange", ""))
        if offset_time is None:
            print(f"警告: 无法从项目 {item.get('_id')} 的editedTimeRange中提取时间范围，跳过该项")
            continue

        try:
            with open(subtitle_path, "r", encoding="utf-8") as file:
                content = file.read().strip()

            if not content:
                print(f"跳过项目 {item.get('_id')}：字幕文件内容为空")
                continue

            valid_items_count += 1
            subtitle_blocks = re.split(r"\n\s*\n", content)

            for block in subtitle_blocks:
                lines = block.strip().split("\n")
                if len(lines) < 3:
                    continue

                time_parts = lines[1].split(" --> ")
                if len(time_parts) != 2:
                    continue

                start_time = parse_time(time_parts[0])
                end_time = parse_time(time_parts[1])
                adjusted_start_time = start_time + offset_time
                adjusted_end_time = end_time + offset_time

                new_block = [
                    str(subtitle_index),
                    f"{format_time(adjusted_start_time)} --> {format_time(adjusted_end_time)}",
                    *lines[2:],
                ]
                merged_subtitles.append("\n".join(new_block))
                subtitle_index += 1
        except Exception as e:
            print(f"处理项目 {item.get('_id')} 的字幕文件时出错: {str(e)}")
            continue

    if not merged_subtitles:
        print(
            f"警告: 没有找到有效的字幕内容，共检查了 {len(subtitle_items)} 个项目，其中 {valid_items_count} 个有有效文件"
        )
        return None

    if output_file is None:
        valid_item = None
        for item in sorted_items:
            subtitle_path = item.get("subtitle")
            if subtitle_path and os.path.exists(subtitle_path):
                valid_item = item
                break

        if not valid_item:
            print("错误: 无法确定输出目录，没有找到有效的字幕文件")
            return None

        dir_path = os.path.dirname(valid_item["subtitle"])
        first_start = parse_edited_time_range(sorted_items[0].get("editedTimeRange", ""))[0]
        last_end = parse_edited_time_range(sorted_items[-1].get("editedTimeRange", ""))[1]

        if first_start and last_end:
            first_start_s = int(first_start.total_seconds())
            last_end_s = int(last_end.total_seconds())

            first_start_h = first_start_s // 3600
            first_start_m = (first_start_s % 3600) // 60
            first_start_sec = first_start_s % 60

            last_end_h = last_end_s // 3600
            last_end_m = (last_end_s % 3600) // 60
            last_end_sec = last_end_s % 60

            first_start_str = f"{first_start_h:02d}_{first_start_m:02d}_{first_start_sec:02d}"
            last_end_str = f"{last_end_h:02d}_{last_end_m:02d}_{last_end_sec:02d}"
            output_file = os.path.join(
                dir_path,
                f"merged_subtitle_{first_start_str}-{last_end_str}.srt",
            )
        else:
            output_file = os.path.join(dir_path, "merged_subtitle.srt")

    merged_content = "\n\n".join(merged_subtitles)
    try:
        with open(output_file, "w", encoding="utf-8") as file:
            file.write(merged_content)
        print(f"字幕文件合并成功: {output_file}，包含 {len(merged_subtitles)} 个字幕条目")
        return output_file
    except Exception as e:
        print(f"写入字幕文件失败: {str(e)}")
        return None
