import os
from pathlib import Path

try:
    from fpdf import FPDF
except Exception:
    print("\ntxt2pdf.py: Import error: fpdf")
    input("Install: pip install fpdf2\n")


def find_font_path(font_path=None):
    candidates = []
    if font_path:
        candidates.append(Path(font_path))

    windows_dir = os.environ.get("SYSTEMROOT")
    if windows_dir:
        candidates.append(Path(windows_dir) / "Fonts" / "msgothic.ttc")

    candidates += [
        Path(r"C:\Windows\Fonts\msgothic.ttc"),
        Path("/System/Library/Fonts/ヒラギノ角ゴシック W4.ttc"),
        Path("/Library/Fonts/Arial Unicode.ttf"),
        Path("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc"),
        Path("/usr/share/fonts/truetype/noto/NotoSansCJKjp-Regular.otf"),
    ]

    for p in candidates:
        if p.is_file():
            return str(p)
    return None


def txt_to_pdf(input_path, output_path=None, font_path=None):
    """
    テキストファイルをPDFに変換します。
    成功時は output_path を返し、失敗時は None を返します。
    """
    input_path = os.path.abspath(input_path)
    if output_path is None:
        output_path = os.path.splitext(input_path)[0] + ".pdf"
    else:
        output_path = os.path.abspath(output_path)

    print(f"  Converting '{os.path.basename(input_path)}' to PDF...")

    try:
        if not os.path.exists(input_path):
            print(f"  Error converting '{input_path}' to PDF: file does not exist")
            return None

        if os.path.getsize(input_path) == 0:
            print(f"  Error converting '{input_path}' to PDF: file is empty")
            return None

        chosen_font = find_font_path(font_path)
        if not chosen_font:
            print("  Error converting to PDF: Japanese font not found")
            return None

        text_content = Path(input_path).read_text(encoding="utf-8")

        pdf = FPDF()
        pdf.set_auto_page_break(auto=True, margin=15)
        pdf.add_page()
        pdf.add_font("DOCFONT", "", chosen_font)
        pdf.set_font("DOCFONT", size=12)

        # 生テキストとして段落・改行をそのまま流し込む
        # 空行もなるべく維持する
        lines = text_content.splitlines()
        if not lines:
            lines = [""]

        for line in lines:
            pdf.multi_cell(0, 7, line if line else " ")
        pdf.output(output_path)

        print(f"  Successfully converted to PDF: '{output_path}'")
        return output_path

    except Exception as e:
        print(f"  Error converting '{input_path}' to PDF: {e}")
        return None


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Convert text file to PDF.")
    parser.add_argument("input_path", help="input text file path")
    parser.add_argument("output_path", nargs="?", default=None, help="output pdf file path")
    parser.add_argument("--font", default=None, help="path to a TTF/OTF/TTC font for Japanese")
    parser.add_argument("--no-pause", action="store_true", help="do not wait for ENTER before exit")
    args = parser.parse_args()

    rc = 0 if txt_to_pdf(args.input_path, args.output_path, font_path=args.font) else 1
    print("\nProgram execution completed.")
    if not args.no_pause:
        input("\nPress ENTER to terminate>>\n")
    raise SystemExit(rc)
