#pip install PyCifRW

from CifFile import ReadCif

def parse_cif_with_pycifrw(filepath):
    """
    PyCifRWライブラリを使用してCIFファイルをパースする関数。
    """
    try:
        cf = ReadCif(filepath)
        print(f"Successfully parsed CIF file: {filepath}")

        # CIFファイル内のすべてのデータブロックを反復処理
        for block_name in cf.keys():
            print(f"\n--- Data Block: {block_name} ---")
            data_block = cf[block_name]

            # データアイテムの表示
            for item_name, item_value in data_block.items():
                if not item_name.startswith('_loop'): # ループアイテムは後で処理
                    print(f"  {item_name}: {item_value}")

            # ループデータの表示 (例: 原子座標)
            # ループが存在する場合、データブロックの属性としてアクセス可能
            # 例: _atom_site_label, _atom_site_type_symbol, _atom_site_fract_x など
            if '_atom_site_label' in data_block.keys():
                print("\n  --- Atom Sites (Loop Data) ---")
                try:
                    # PyCifRWはループデータをpandas DataFrameのように扱えることが多い
                    # ここではリストのリストとしてアクセス
                    labels = data_block['_atom_site_label']
                    types = data_block['_atom_site_type_symbol']
                    xs = data_block['_atom_site_fract_x']
                    ys = data_block['_atom_site_fract_y']
                    zs = data_block['_atom_site_fract_z']

                    print(f"    {'Label':<10} {'Type':<10} {'x':<10} {'y':<10} {'z':<10}")
                    for i in range(len(labels)):
                        print(f"    {labels[i]:<10} {types[i]:<10} {float(xs[i]):<10.6f} {float(ys[i]):<10.6f} {float(zs[i]):<10.6f}")
                except KeyError:
                    print("    Atom site loop data is incomplete.")
                except Exception as e:
                    print(f"    Error processing atom site loop: {e}")
            else:
                print("  No atom site loop found in this block.")

    except FileNotFoundError:
        print(f"Error: File not found at {filepath}")
    except Exception as e:
        print(f"An error occurred while parsing the CIF file: {e}")

# --- 使用例 ---
if __name__ == "__main__":
    # テスト用のダミーCIFファイルを作成
    # 実際のCIFファイルパスに置き換えてください
    dummy_cif_content = """
data_example_block
_cell_length_a 10.0
_cell_length_b 10.0
_cell_length_c 10.0
_cell_angle_alpha 90.0
_cell_angle_beta 90.0
_cell_angle_gamma 90.0
_symmetry_space_group_name_H-M 'P 1'

loop_
_atom_site_label
_atom_site_type_symbol
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
Na Na 0.0 0.0 0.0
Cl Cl 0.5 0.5 0.5

data_another_block
_chemical_formula_sum 'NaCl'
_chemical_formula_structural 'NaCl'
"""
    with open("test.cif", "w") as f:
        f.write(dummy_cif_content)

    cif_file_path = "test.cif"
    parse_cif_with_pycifrw(cif_file_path)

    # 実際のCIFファイルがある場合は、パスを指定して試してみてください
    # parse_cif_with_pycifrw("path/to/your/actual_crystal.cif")