#!/usr/bin/env python3
"""
add-lines-vietnamese.py — Thêm dòng trống giữa các đoạn văn cho dễ đọc

Công dụng:
  Sau khi chạy merge-lines-vietnamese.py, các đoạn văn đã được nối lại nhưng
  có thể thiếu dòng trống giữa các đoạn. Script này thêm dòng trống giữa
  các đoạn văn liền kề (không có blank line) để tăng khả năng đọc.

Nguyên tắc:
  - Nếu hai dòng text (không phải heading/separator/URL/blank) nằm liền kề
    → thêm một dòng trống giữa chúng.
  - Heading / separator → luôn được theo sau bởi dòng trống (nếu thiếu).
  - Giữ nguyên các dòng trống đã có.
  - Không thêm dòng trống ở cuối file.

Cách dùng:
  python3 add-lines-vietnamese.py input.md [output.md]
  - Nếu không có output, ghi đè tại chỗ
"""

import sys
from pathlib import Path


def add_blank_lines(text: str) -> str:
    """
    Thêm dòng trống giữa các đoạn văn liền kề.
    """
    lines = text.splitlines()
    result = []

    for i, line in enumerate(lines):
        stripped = line.strip()
        result.append(line)

        # Kiểm tra: có dòng kế tiếp không?
        if i + 1 >= len(lines):
            break

        next_stripped = lines[i + 1].strip()
        if not next_stripped:
            # Dòng kế đã là blank → không cần thêm
            continue

        # Nếu dòng hiện tại là heading → thêm blank sau
        if stripped.startswith('#'):
            result.append('')
            continue

        # Nếu dòng hiện tại là separator → thêm blank sau
        if stripped.startswith('---o0o--') or stripped == '---':
            result.append('')
            continue

        # Nếu dòng hiện tại là URL → thêm blank sau
        if stripped.startswith(('http://', 'https://')):
            result.append('')
            continue

        # Nếu dòng hiện tại là text VÀ dòng kế cũng là text (không blank)
        # → thêm dòng trống phân cách đoạn
        if stripped and next_stripped:
            # Chỉ thêm nếu dòng kế không phải heading/separator/URL
            if not (next_stripped.startswith('#')
                    or next_stripped.startswith('---o0o--')
                    or next_stripped == '---'
                    or next_stripped.startswith(('http://', 'https://'))):
                result.append('')

    return '\n'.join(result)


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 add-lines-vietnamese.py input.md [output.md]", file=sys.stderr)
        sys.exit(1)

    input_path = Path(sys.argv[1])
    if not input_path.exists():
        print(f"Error: File not found: {input_path}", file=sys.stderr)
        sys.exit(1)

    output_path = Path(sys.argv[2]) if len(sys.argv) > 2 else input_path

    raw = input_path.read_text(encoding='utf-8')
    result = add_blank_lines(raw)
    output_path.write_text(result, encoding='utf-8')

    original_lines = len(raw.splitlines())
    result_lines = len(result.splitlines()) if result else 0
    print(f"✅ Xong! {input_path.name}")
    print(f"   {original_lines} dòng → {result_lines} dòng")
    print(f"   → {output_path}")


if __name__ == '__main__':
    main()
