import os
import re

def timestamp_to_ms(ts_string):
    match = re.match(r'(\d{2}):(\d{2}):(\d{2}),(\d{3})', ts_string)
    if not match: return 0
    h, m, s, ms = map(int, match.groups())
    return (h * 3600000) + (m * 60000) + (s * 1000) + ms

def validate_subtitles(directory, extension=".srt"):
    ts_regex = r'(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})'
    cjk_pattern = re.compile(r'[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]')

    for filename in os.listdir(directory):
        if not filename.endswith(extension): continue
        
        file_path = os.path.join(directory, filename)
        file_has_issue = False
        last_end_time = -1
        block_count = 0
        
        # Encoding safety
        try:
            with open(file_path, 'r', encoding='utf-8-sig') as f:
                lines = f.readlines()
        except UnicodeDecodeError:
            with open(file_path, 'r', encoding='latin-1') as f:
                lines = f.readlines()
            print(f"--- Note: {filename} read with 'latin-1' ---")

        for i, line in enumerate(lines):
            clean_line = line.strip()
            
            # Strict Block Detection
            is_new_block = False
            if clean_line.isdigit() and (i + 1 < len(lines)):
                if re.match(ts_regex, lines[i+1].strip()):
                    is_new_block = True

            if is_new_block:
                block_count += 1
                issue_log = []

                # 1. Blank Line Check
                if block_count > 1:
                    if i > 0 and lines[i-1].strip() != "":
                        issue_log.append(f"[Spacing Error] Block {block_count}: Missing blank line before index.")

                # 2. Timing Checks
                ts_line = lines[i+1].strip()
                ts_match = re.search(ts_regex, ts_line)
                if ts_match:
                    start_str, end_str = ts_match.groups()
                    start_ms = timestamp_to_ms(start_str)
                    end_ms = timestamp_to_ms(end_str)

                    if start_ms >= end_ms:
                        issue_log.append(f"[Logic Error] Block {block_count}: {start_str} -> {end_str}")
                    if start_ms < last_end_time:
                        issue_log.append(f"[Sequence Error] Block {block_count} overlaps previous.")
                    
                    last_end_time = end_ms

                # 3. EMPTY TEXT & CJK CHECK
                # Look at lines following the timestamp (i+2 onwards)
                j = i + 2
                has_text = False
                while j < len(lines) and lines[j].strip() != "":
                    text_content = lines[j].strip()
                    if text_content:
                        has_text = True
                        # Check for CJK in the text we found
                        # found_cjk = cjk_pattern.findall(text_content)
                        # if found_cjk:
                        #    issue_log.append(f"[Language Warning] CJK found: {''.join(set(found_cjk))}")
                    j += 1
                
                if not has_text:
                    issue_log.append(f"[Content Error] Block {block_count}: No subtitle text found (empty block).")

                # REPORTING
                if issue_log:
                    if not file_has_issue:
                        print(f"\n>>> ISSUES IN: {filename}")
                        file_has_issue = True
                    for error in issue_log:
                        print(f"    {error}")

        if file_has_issue:
            input("\nPress Enter to continue...")

    print("\nScan Complete.")

# Path updated from your previous error log
validate_subtitles('.', extension=".srt")
