# run_workflow.py
"""
CIF置換ワークフロー実行スクリプト (マスタープログラム)

[概要]
このスクリプトは、CIFファイルの原子置換に関する一連の処理を自動で実行するための
メインプログラムです。ユーザーはこのファイルのみを操作します。
YAML形式の設定ファイル (例: cif_config.yaml) を読み込み、以下の処理を順に実行します。

1. `cif_templater.py` を呼び出し、元のCIFファイルから置換用のテンプレートを作成。
2. `cif_generator.py` を呼び出し、1で作成したテンプレートと設定ファイルの内容に
   基づいて、最終的な置換CIFファイルを一括で生成します。

[使い方]
1. 設定ファイルのテンプレートを生成する (初回のみ):
   ターミナルで以下のコマンドを実行すると、`cif_config.yaml` のひな形が作成されます。
   $ python run_workflow.py --init

2. 設定ファイルを編集する:
   生成された `cif_config.yaml` をテキストエディタで開き、
   - `base_cif`: 元にするCIFファイルのパス
   - `experiment_name`: 出力フォルダ名
   - `substitutions`: 置換したい元素のリスト
   などを、ご自身の実験に合わせて編集します。

3. ワークフローを実行する:
   設定ファイルの編集後、以下のコマンドで一連の処理を実行します。
   $ python run_workflow.py --config cif_config.yaml
   (`--config` を省略した場合は、デフォルトで 'cif_config.yaml' が使われます)
"""

import argparse
import yaml
import json
import os
import shutil
from cif_templater import CifTemplateGenerator
from cif_generator import CifGenerator

# create_yaml_template(), run_workflow(), main(), and __main__ blocks are unchanged...

def create_yaml_template(config_filename='cif_config.yaml', template_filename='cif_config.template.yaml'):
    """
    Generates a config YAML file from an external template file.
    """
    try:
        script_dir = os.path.dirname(os.path.realpath(__file__))
        source_template_path = os.path.join(script_dir, template_filename)
    except NameError:
        source_template_path = template_filename

    if not os.path.exists(source_template_path):
        print(f"❌ エラー: テンプレート '{source_template_path}' が見つかりません。")
        print(f"   '{template_filename}' がスクリプトと同じディレクトリにあるか確認してください。")
        return

    if os.path.exists(config_filename):
        overwrite = input(f"⚠️  カレントディレクトリに '{config_filename}' が既に存在します。上書きしますか？ (y/n): ").lower()
        if overwrite != 'y':
            print("❌ 操作を中断しました。")
            return
    
    shutil.copy(source_template_path, config_filename)
    
    print(f"✅ 設定ファイル '{config_filename}' をカレントディレクトリに作成しました。")
    print("   このファイルを編集して、再度 'python run_workflow.py' を実行してください。")


def run_workflow(config_path):
    """
    Executes the full workflow based on a YAML config file.
    """
    print(f"📖 設定ファイル '{config_path}' を読み込んでいます...")
    if not os.path.exists(config_path):
        print(f"❌ エラー: 設定ファイル '{config_path}' が見つかりません。")
        print(f"   'python {os.path.basename(__file__)} --init' を実行して、テンプレートを先に作成してください。")
        return

    with open(config_path, 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f)
    
    base_cif = config['base_cif']
    
    try:
        templater = CifTemplateGenerator(base_cif)
        template_path, meta_path = templater.run()
    except (FileNotFoundError, ValueError) as e:
        print(f"❌ テンプレート作成中にエラーが発生しました: {e}")
        return

    with open(meta_path, 'r', encoding='utf-8') as f:
        metadata = json.load(f)
        
    generator_config = {
        'template_file': template_path,
        'experiment_name': config.get('experiment_name', 'cif_run'),
        'roles': metadata['roles'],
        'stoichiometry': metadata['stoichiometry'],
        'substitutions': config['substitutions']
    }

    try:
        generator = CifGenerator(generator_config)
        generator.run()
    except Exception as e:
        print(f"❌ CIFファイル生成中にエラーが発生しました: {e}")


def main():
    """
    コマンドライン引数を解析し、適切な関数を呼び出す。
    """
    parser = argparse.ArgumentParser(
        description="設定ファイルに基づき、CIF置換ワークフロー全体を実行します。",
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument(
        '--config',
        type=str,
        default='cif_config.yaml',
        help="実験設定が記述されたYAMLファイルのパス。\nデフォルト: cif_config.yaml"
    )
    parser.add_argument(
        '--init',
        action='store_true',
        help="設定ファイル 'cif_config.yaml' のテンプレートを生成します。"
    )
    args = parser.parse_args()

    if args.init:
        create_yaml_template()
    else:
        run_workflow(args.config)


if __name__ == '__main__':
    main()