from __future__ import annotations

from pathlib import Path

from docx import Document
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas


def save_txt(text: str, path: str) -> None:
    Path(path).write_text(text, encoding="utf-8")


def save_docx(text: str, path: str) -> None:
    doc = Document()
    for para in text.splitlines() or [""]:
        doc.add_paragraph(para)
    doc.save(path)


def save_pdf(text: str, path: str) -> None:
    c = canvas.Canvas(path, pagesize=letter)
    _width, height = letter

    x = 72
    y = height - 72
    line_height = 14

    def new_page():
        nonlocal y
        c.showPage()
        y = height - 72

    for line in (text.splitlines() or [""]):
        chunks = []
        cur = line
        while len(cur) > 80:
            split_pos = cur[80:].index(" ") if " " in cur[80:] else 0
            chunks.append(cur[:80 + split_pos].lstrip())
            cur = cur[80 + split_pos:]
        chunks.append(cur.lstrip())

        for chunk in chunks:
            if y < 72:
                new_page()
            c.drawString(x, y, chunk)
            y -= line_height

    c.save()
