#!/usr/bin/env python3
"""
split-bold-paragraphs.py — Tách dòng có bold + uppercase continuation

Quy tắc:
  Nếu một dòng body text có **bold** và sau dấu ** đóng có chữ bắt đầu
  bằng chữ hoa (coi như câu/section mới), thì chèn dòng trống giữa phần
  bold và phần còn lại.

  Không tách nếu nội dung trong **...** kết thúc bằng dấu hai chấm (:)
  (đây là label inline như Hỏi:, Đáp:, Ghi chú :).

Ví dụ:
  Input:  **Bốn Nguyên Nhân Của Sự Chết** Cái chết xảy ra do...
  Output: **Bốn Nguyên Nhân Của Sự Chết**
           (dòng trống)
           Cái chết xảy ra do...

Cách dùng:
  python3 split-bold-paragraphs.py [input.md [output.md]]
  Nếu không có đối số, xử lý file bold mặc định và ghi đè.
"""

import re
import sys
from pathlib import Path

# ── Đường dẫn mặc định ────────────────────────────────────────────────────
DEFAULT_INPUT = "/home/tuan-nguyen/Documents/Doc/Chanh-Kien-Va-Nghiep-bold.md"

# Mẫu regex tìm **...** (non-greedy, không lồng nhau)
BOLD_PATTERN = re.compile(r'\*\*(.+?)\*\*')

# Ký tự Latin + chữ cái tiếng Việt có dấu hoa
VIET_UPPER = set("ABCDĐEFGHIJKLMNOPQRSTUVWXYZÀÁẢÃẠÂẦẤẨẪẬĂẰẮẲẴẶÈÉẺẼẸÊỀẾỂỄỆÌÍỈĨỊÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢÙÚỦŨỤƯỪỨỬỮỰỲÝỶỸ")


def is_heading_or_special(line: str) -> bool:
    """Kiểm tra dòng cần bỏ qua (heading ##/###, separator, blank, URL)."""
    stripped = line.strip()
    if not stripped:
        return True
    if stripped.startswith('##'):
        return True
    if stripped.startswith('---o0o') or stripped == '---':
        return True
    if stripped.startswith('http://') or stripped.startswith('https://'):
        return True
    return False


def first_alpha_uppercase(text: str) -> bool:
    """
    Tìm ký tự chữ cái đầu tiên trong text.
    Trả về True nếu nó là uppercase.
    Bỏ qua whitespace ở đầu, nhưng KHÔNG bỏ qua dấu hai chấm. 
    Nếu ký tự không-whitespace đầu tiên là ':' → return False (label-style).
    """
    for ch in text:
        if ch == ':':
            return False   # dấu : sau ** ngăn tách (label-style)
        if ch.isalpha():
            return ch.isupper()
    return False


def split_bold_line(line: str) -> list:
    """
    Xử lý một dòng body text:
    - Tìm cặp **...** cuối cùng
    - Nếu content trong **...** kết thúc bằng ':' → không tách (inline label)
    - Nếu text sau ** đóng bắt đầu bằng uppercase → tách
    Trả về list các dòng kết quả.
    """
    stripped = line.rstrip('\n\r')
    raw = stripped  # keep original whitespace for before ** marker

    matches = list(BOLD_PATTERN.finditer(stripped))
    if not matches:
        return [stripped]

    # Chỉ xử lý match cuối cùng
    last = matches[-1]
    before = stripped[:last.start()]    # text trước ** mở
    content = last.group(1)             # nội dung trong **...**
    after = stripped[last.end():]       # text sau ** đóng

    # (1) Nếu nội dung bold kết thúc bằng ':' → label inline, không tách
    if content.rstrip().endswith(':'):
        return [stripped]

    # (2) Nếu không còn gì sau ** → không cần tách
    if not after.strip():
        return [stripped]

    # (3) Kiểm tra ký tự chữ đầu tiên sau ** đóng có phải uppercase không
    if not first_alpha_uppercase(after):
        return [stripped]

    # --- TÁCH ---
    bold_line = before + '**' + content + '**'
    rest_line = after.lstrip()  # bỏ khoảng trắng thừa đầu

    return [bold_line, '', rest_line]


def process_file(input_path: str, output_path: str) -> dict:
    """Xử lý toàn bộ file, trả về thống kê."""
    lines = Path(input_path).read_text(encoding='utf-8').splitlines(keepends=True)
    output_lines = []
    stats = {
        'total': len(lines),
        'skipped_special': 0,
        'split_lines': 0,
    }

    for line in lines:
        raw_stripped = line.rstrip('\n\r')

        if is_heading_or_special(raw_stripped):
            stats['skipped_special'] += 1
            output_lines.append(raw_stripped)
            continue

        result = split_bold_line(raw_stripped)

        if len(result) > 1:
            # Đã tách thành [bold_line, '', rest_line]
            stats['split_lines'] += 1

        output_lines.extend(result)

    content = '\n'.join(output_lines) + '\n'
    Path(output_path).write_text(content, encoding='utf-8')

    stats['output_lines'] = len(output_lines)
    return stats


def main():
    input_path = DEFAULT_INPUT

    if len(sys.argv) >= 2:
        input_path = sys.argv[1]
    output_path = sys.argv[2] if len(sys.argv) >= 3 else input_path

    if not Path(input_path).exists():
        print(f"❌ File không tồn tại: {input_path}", file=sys.stderr)
        sys.exit(1)

    print(f"📖 Đọc:  {input_path}")
    print(f"✍️  Ghi:  {output_path}")

    stats = process_file(input_path, output_path)

    print(f"\n📊 Kết quả xử lý:")
    print(f"   Tổng dòng input:    {stats['total']}")
    print(f"   Bỏ qua (đặc biệt):  {stats['skipped_special']}")
    print(f"   ✅ Đã tách:          {stats['split_lines']}")
    print(f"   Tổng dòng output:   {stats['output_lines']}")


if __name__ == '__main__':
    main()
