import os
import sys
import argparse
try:
    import pdfplumber
except:
    print("\npptx2pdf_recursive.py: Import error: pdfplumber")
    input("Install: pip install pdfplumber\n")


def convert(infile_path, outfile_path):
    if not os.path.exists(infile_path):
        print(f"エラー: 指定されたファイルが見つかりません: {infile_path}", file=sys.stderr)
        return

    if outfile_path is None:
        filename_without_ext = os.path.splitext(os.path.basename(infile_path))[0]
        outfile_path = os.path.join(os.path.dirname(infile_path), f"{filename_without_ext}.md")

    try:
        # PDFファイルを開く
        with pdfplumber.open(infile_path) as pdf:
            with open(outfile_path, 'w', encoding='utf-8') as md_file:
                # ファイル名をH1見出しとして書き込む
                md_file.write(f"# {filename_without_ext}\n\n")

                # 各ページをループ
                for page in pdf.pages:
                    # ページ番号をH2見出しとして書き込む
                    md_file.write(f"## ページ {page.page_number}\n\n")

                    # ページのテキストを抽出
                    # clean=Trueは、ハイフン結合された単語を元に戻すなどの処理を行います
                    text = page.extract_text(x_tolerance=1, y_tolerance=3, layout=True)
                    if text:
                        md_file.write(text.strip())
                    
                    # ページの区切り線を追加
                    md_file.write("\n\n---\n\n")

        print(f"変換が完了しました: {outfile_path}")

    except Exception as e:
        print(f"エラーが発生しました: {e}", file=sys.stderr)
        sys.exit(1)

def main():
    """
    PDFファイルをMarkdownに変換するメイン関数
    """
    parser = argparse.ArgumentParser(
        description='PDFファイルをMarkdownに変換します。',
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument(
        '--infile',
        type=str,
        help='変換するPDFファイルのパス'
    )
    parser.add_argument(
        '--outfile',
        type=str,
        help='出力ファイルのパス'
    )
    
    args = parser.parse_args()
    
    infile_path = args.infile
    outfile_path = args.get("outfile", None)
    convert(infile_path, outfile)

if __name__ == "__main__":
    main()