# pip install fpdf2

import os
import sys
import argparse
from fpdf import FPDF

def initialize():
    parser = argparse.ArgumentParser(description="Convert text files to PDF.")
    parser.add_argument('infile', type=str, help='Input text file path.')
    parser.add_argument('outfile', type=str, nargs='?', default=None, help='Output PDF file path.')
    return parser.parse_args()

def replace_path(path, ext):
    if not path:
        print("Error: 入力パスが空です。", file=sys.stderr)
        sys.exit(1)
    return os.path.splitext(path)[0] + ext

def convert_to_pdf(infile, outfile=None):
    if not os.path.exists(infile):
        print(f"Error: ファイル '{infile}' が存在しません。", file=sys.stderr)
        return False
    if os.path.getsize(infile) == 0:
        print(f"Error: 入力ファイル '{infile}' は空です。", file=sys.stderr)
        return False

    if outfile is None:
        outfile = replace_path(infile, '.pdf')

    try:
        # テキストファイルの内容を読み込む
        with open(infile, "r", encoding="utf-8") as file:
            text_content = file.read()

        # FPDFオブジェクトを初期化
        pdf = FPDF()

        # 日本語フォントを追加
        # `fpdf2`にフォントの場所を教える必要があります
        windows_dir = os.environ.get('SYSTEMROOT')
#        pdf.add_font("IPAexGothic", fname="ipaexg.ttf")
        pdf.add_font("MS-Gothic", fname=f"{windows_dir}\\Fonts\\msgothic.ttc")
        
        pdf.add_page()
        
        # 日本語フォントに設定を変更
#        pdf.set_font("IPAexGothic", size=12)
        pdf.set_font("MS-Gothic", size=12)

        # テキストをPDFに追加
        pdf.multi_cell(0, 10, text_content)

        # PDFファイルを保存
        pdf.output(outfile)
        
        print("Conversion successful.")
        print(f"Saved to: {outfile}")
        return True

    except Exception as e:
        print(f"Error: PDF変換中にエラーが発生しました - {e}", file=sys.stderr)
        return False

def main():
    args = initialize()
    
    print("\nテキストファイルをPDFファイルに変換します")
    print(f"入力ファイル: {args.infile}")
    
    convert_to_pdf(args.infile, args.outfile)

if __name__ == "__main__":
    main()