import os
import fnmatch
import argparse


def find_output_filename(template, idx):
        while True:
            output_path = template.format(idx)
            if os.path.exists(output_path):
                idx += 1
                continue

            break
        return output_path, idx + 1

def create_markdown_from_files(root_dir, filemasks, max_bytes, prefix):
    """
    指定された条件でファイルを検索し、Markdownファイルに保存します。

    Args:
        root_dir (str): 検索を開始するルートディレクトリ。
        filemask (str): ファイルマスク (例: "*.py", "*.js")。
        max_bytes (int): 各Markdownファイルの最大バイト数。
    """

    # 出力ファイル名とインデックスを初期化
    output_filename_template = prefix + "_{:04d}.md"
    file_index = 1
    current_file_size = 0
    output_path, file_index = find_output_filename(output_filename_template, file_index)
    
    def filematch(filename, filemasks):
        masks = filemasks.split(';')
        for fmask in masks:
            if fnmatch.fnmatch(filename, fmask): return True
        return False

    # 書き込みモード
    output_file = open(output_path, "a", encoding="utf-8")
    try:
        # ディレクトリツリーを巡回
        for dirpath, _, filenames in os.walk(root_dir):
            for filename in filenames:
                if filematch(filename, filemasks):
#                if fnmatch.fnmatch(filename, filemask):
                    full_path = os.path.join(dirpath, filename)
                    
                    try:
                        with open(full_path, 'r', encoding='utf-8') as f:
                            content = f.read()

                        # Markdown形式のコンテンツを作成
                        markdown_content = f"### {full_path}\n\n#=======\n{content}\n#=======\n\n"
#                        markdown_content = f"### {full_path}\n\n```\n{content}\n```\n\n"
                        markdown_bytes = markdown_content.encode('utf-8')
                        
                        # ファイルサイズが最大バイト数を超えた場合、新しいファイルを作成
                        if current_file_size + len(markdown_bytes) > max_bytes:
                            output_file.close()
#                            file_index += 1
                            output_path, file_index = find_output_filename(output_filename_template, file_index)
#                            output_path = output_filename_template.format(file_index)
                            output_file = open(output_path, "a", encoding="utf-8")
                            current_file_size = 0
                        
                        # Markdownファイルを書き込み
                        output_file.write(markdown_content)
                        current_file_size += len(markdown_bytes)
                        print(f"Added {full_path} to {output_path}")

                    except UnicodeDecodeError:
                        print(f"Skipped {full_path} due to encoding error.")
    
    finally:
        # 最後に開いているファイルをクローズ
        if output_file and not output_file.closed:
            output_file.close()

def main():
    """
    コマンドライン引数を解析し、メインの処理を実行します。
    """
    # ArgumentParserオブジェクトを作成
    parser = argparse.ArgumentParser(description="指定されたディレクトリ以下のファイルをMarkdownに保存します。")
    
    # 引数を追加
    parser.add_argument("root_dir",    type=str, default=".",      help="検索を開始するルートディレクトリ")
    parser.add_argument("filemasks",   type=str, default="*.py",   help="ファイルマスク（例: *.py;*.p?）")
    parser.add_argument("--max_bytes", type=int, default=20000000, help="各Markdownファイルの最大バイト数")
    parser.add_argument("--prefix",    type=str, default="output", help="出力ファイルのベース名")

    # 引数を解析
    args = parser.parse_args()
    
    # メインの関数を呼び出し
    create_markdown_from_files(args.root_dir, args.filemasks, args.max_bytes, args.prefix)

if __name__ == "__main__":
    main()