"""
Tách nội dung từng Điều trong hợp đồng - giữ nguyên text.
"""
import re


def split_contract_by_dieu(text: str) -> list[dict]:
    DIEU_RE = re.compile(r'^ĐIỀU\s+(\d+)\.\s*(.+)$')

    segments = []
    current_dieu = None
    current_title = ""
    current_content = []

    for line in text.splitlines():
        line_stripped = line.strip()
        if not line_stripped:
            continue

        m = DIEU_RE.match(line_stripped)
        if m:
            if current_dieu is not None:
                segments.append({
                    "dieu": current_dieu,
                    "tieu_de": current_title,
                    "noi_dung": "\n".join(current_content),
                })
            current_dieu = int(m.group(1))
            current_title = m.group(2).strip()
            current_content = []
            continue

        if current_dieu is not None:
            current_content.append(line_stripped)

    if current_dieu is not None:
        segments.append({
            "dieu": current_dieu,
            "tieu_de": current_title,
            "noi_dung": "\n".join(current_content),
        })

    return segments


if __name__ == "__main__":
    with open("data.txt", "r", encoding="utf-8") as f:
        text = f.read()

    results = split_contract_by_dieu(text)

    # Ghi ra file text, mỗi Điều cách nhau bằng dấu ===
    output_lines = []
    for seg in results:
        output_lines.append(f"ĐIỀU {seg['dieu']}. {seg['tieu_de']}")
        output_lines.append(seg["noi_dung"])
        output_lines.append("\n" + "=" * 60 + "\n")

    output_text = "\n".join(output_lines)

    with open("output_dieu.txt", "w", encoding="utf-8") as f:
        f.write(output_text)

    print(f"Done! Tach duoc {len(results)} Dieu -> output_dieu.txt")
