"""
Advance/OF-DFT example: read structures from files, calculate them in a batch,
and save the results (energy, forces, stress, atomic charges) to an extended XYZ file.

Copyright (C) 2026 AdvanceSoft Corporation, All rights reserved.
"""

import csv
import glob
import os

from ase.build import bulk
from ase.io import read, write

from aofdft.calculator import AOFDFTCalculator

VPS_DIR = "path/to/DFT_DATA19_AS/VPS"  # edit these two paths for your environment
PAO_DIR = "path/to/DFT_DATA19_AS/PAO"

INPUT_DIR = "structures"         # put your own CIF / POSCAR / xyz ... files here
RESULT    = "results.extxyz"     # all calculated structures with their results
SUMMARY   = "summary.csv"        # one line per structure

# --- create sample input files (only when the folder does not exist yet)
if not os.path.isdir(INPUT_DIR):
    os.makedirs(INPUT_DIR)
    write(f"{INPUT_DIR}/Si.cif",      bulk("Si", "diamond", a=5.43, cubic=True))                # 8 atoms
    write(f"{INPUT_DIR}/SiC.cif",     bulk("SiC", "zincblende", a=4.36).repeat((2, 2, 2)))      # 16 atoms
    write(f"{INPUT_DIR}/Al_POSCAR",   bulk("Al", "fcc", a=4.05, cubic=True).repeat((2, 2, 2)),  # 32 atoms
          format="vasp")

if os.path.exists(RESULT):
    os.remove(RESULT)

rows = []
for path in sorted(glob.glob(f"{INPUT_DIR}/*")):
    name  = os.path.basename(path)
    atoms = read(path)  # the format is detected from the file name / content

    atoms.calc = AOFDFTCalculator(
        console       = False,
        logging_file  = f"{name}.log",  # one log file per structure
        kin_type      = "AS26",
        kin_model     = "Crystal26",
        vps_dir       = VPS_DIR,
        pao_dir       = PAO_DIR,
        scf_must_conv = True,
    )

    try:
        energy = atoms.get_potential_energy()
        forces = atoms.get_forces()
        atoms.get_stress()  # calculated here so that it is saved to the extended XYZ file
    except Exception as err:  # e.g. the SCF did not converge: record it and go on
        print(f"{name:12s} FAILED: {err}")
        rows.append({"name": name, "formula": atoms.get_chemical_formula(), "status": "failed"})
        continue

    fmax = (forces**2).sum(axis=1).max()**0.5  # largest force on an atom
    rows.append({
        "name"            : name,
        "formula"         : atoms.get_chemical_formula(),
        "status"          : "ok",
        "n_atoms"         : len(atoms),
        "energy_eV"       : f"{energy:.6f}",
        "energy_per_atom" : f"{energy / len(atoms):.6f}",
        "fmax_eV_A"       : f"{fmax:.4f}",
        "e_fermi_eV"      : f"{atoms.calc.e_fermi:.4f}",
    })
    print(f"{name:12s} {atoms.get_chemical_formula():6s} E = {energy:12.6f} eV  Fmax = {fmax:6.4f} eV/A")

    # energy, forces and stress are written from atoms.calc;
    # Mulliken charges are in atoms.arrays["charge"] and written as a per-atom column
    atoms.info["source"] = name
    write(RESULT, atoms, append=True)

columns = ["name", "formula", "status", "n_atoms", "energy_eV", "energy_per_atom",
           "fmax_eV_A", "e_fermi_eV"]
with open(SUMMARY, "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=columns)  # missing values are left empty
    writer.writeheader()
    writer.writerows(rows)
print(f"Saved {RESULT} and {SUMMARY}")

# --- read the results back, e.g. for analysis or as training data.
#     ASE stores the results in a SinglePointCalculator; the "charge" column is
#     returned by get_charges()
for atoms in read(RESULT, index=":"):
    charges = atoms.get_charges().round(3) + 0.0  # adding 0.0 turns -0.0 into 0.0
    print(f"{atoms.info['source']:12s} E = {atoms.get_potential_energy():12.6f} eV, "
          f"charges = {charges.min():+.3f} ... {charges.max():+.3f}")
