"""Native two-face water/MgO(100) continuum single point.

Run each clean/covered and dry/wet case separately through vq. This is a
fixed-geometry numerical demonstration, not a converged adsorption model.
The bilayer is the geometry of examples/semiempirical/11_msindo_ccm.py.
"""

import argparse
import numpy as np
import vibeqc as v
from vibeqc.output.slab_solvation import write_slab_result


def geometry(covered=False, repeat=1, height=30.0, layers=2):
    nx, ny = (repeat, repeat) if isinstance(repeat, int) else repeat
    if any(not isinstance(n, int) or n < 1 for n in (nx, ny)):
        raise ValueError("In-plane repeat counts must be positive integers")
    a = 2.105
    if not isinstance(layers, int) or layers < 2 or layers % 2:
        raise ValueError("The mirrored MgO example requires an even layer count >= 2")
    atoms = [
        (12 if (i + j + k) % 2 == 0 else 8, a*i, a*j, a*k)
        for k in range(layers) for j in range(2) for i in range(2)
    ]
    top = a * (layers - 1)
    if covered:
        water = [
            (8, a, 0, top + 2.2),
            (1, a + 0.76, 0, top + 2.76),
            (1, a - 0.76, 0, top + 2.76),
        ]
        atoms += water + [(z, a - x, -y, top - h) for z, x, y, h in water]
    bohr = 1.8897261246257702
    cell = [
        v.Atom(z, bohr * np.array([x + 2 * a * i, y + 2 * a * j, h]))
        for i in range(nx)
        for j in range(ny)
        for z, x, y, h in atoms
    ]
    system = v.slab_2d(
        [2 * a * nx * bohr, 0, 0], [0, 2 * a * ny * bohr, 0], cell
    )
    lattice = np.array(system.lattice)
    lattice[:, 2] = [0.0, 0.0, height]
    system.lattice = lattice
    return system


def main():
    parser = argparse.ArgumentParser(__doc__)
    parser.add_argument("--covered", action="store_true")
    parser.add_argument("--wet", action="store_true")
    parser.add_argument("--model", choices=["cpcm", "cosmo"], default="cpcm")
    parser.add_argument("--epsilon", type=float, default=78.39)
    parser.add_argument("--nleb", type=int, default=302)
    parser.add_argument("--normal-quadrature", type=int, default=160)
    parser.add_argument("--accessibility-spacing", type=float, default=0.0125)
    parser.add_argument(
        "--accessibility-mesh", nargs=2, type=int, default=(640, 640),
        metavar=("NX", "NY"),
        help="In-plane counts for one example cell; multiplied by each repeat",
    )
    parser.add_argument("--energy-tolerance", type=float, default=1e-9)
    parser.add_argument("--gradient-tolerance", type=float, default=1e-7)
    parser.add_argument("--cutoff", type=float, default=18.0)
    parser.add_argument("--nuclear-cutoff", type=float, default=25.0)
    parser.add_argument("--host-normal-points", type=int, default=401,
                        help="Host normal Fourier points, distinct from the surface quadrature")
    parser.add_argument(
        "--host-ewald-alpha", type=float, default=0.4,
        help="Host Ewald split in inverse bohr; converge with the real-space cutoffs",
    )
    parser.add_argument("--partition-radius", type=float, default=10.0)
    parser.add_argument("--radial-points", type=int, default=99)
    parser.add_argument("--lebedev-order", type=int, default=53)
    parser.add_argument("--repeat", type=int, default=1)
    parser.add_argument("--repeat-x", type=int)
    parser.add_argument("--repeat-y", type=int)
    parser.add_argument("--height", type=float, default=30.0)
    parser.add_argument("--layers", type=int, default=2)
    parser.add_argument("--basis", default="sto-3g")
    parser.add_argument("--reciprocal-cache-mib", type=float,
                        help="Reciprocal workspace budget; default uses the shared memory policy")
    parser.add_argument("--threads", type=int, default=2)
    parser.add_argument("--output", default="mgo-slab")
    args = parser.parse_args()
    v.set_num_threads(args.threads)
    args.repeat_x = args.repeat if args.repeat_x is None else args.repeat_x
    args.repeat_y = args.repeat if args.repeat_y is None else args.repeat_y
    system = geometry(args.covered, (args.repeat_x, args.repeat_y), args.height, args.layers)
    basis = v.BasisSet(system.unit_cell_molecule(), args.basis)
    if args.accessibility_mesh is not None:
        args.accessibility_mesh = tuple(
            n * repeat for n, repeat in zip(
                args.accessibility_mesh, (args.repeat_x, args.repeat_y)
            )
        )
    solvation = (
        v.SlabSolvationOptions(
            cavity=v.ISwiGCavity(args.nleb),
            model=v.NativePCM(model=args.model, epsilon=args.epsilon),
            normal_quadrature=args.normal_quadrature,
            accessibility_spacing=args.accessibility_spacing,
            accessibility_mesh=args.accessibility_mesh,
        )
        if args.wet
        else None
    )
    result = v.run_periodic_job(
        system,
        basis,
        method="RKS",
        functional="pbe",
        kpoints=(1, 1, 1),
        solvation=solvation,
        slab_numerics=v.SlabRKSNumerics(
            lattice_cutoff_bohr=args.cutoff,
            nuclear_cutoff_bohr=args.nuclear_cutoff,
            ewald_alpha=args.host_ewald_alpha,
            reciprocal_normal_points=args.host_normal_points,
            reciprocal_cache_mib=args.reciprocal_cache_mib,
            partition_radius_bohr=args.partition_radius,
            radial_points=args.radial_points,
            lebedev_order=args.lebedev_order,
        ),
        max_iter=100,
        conv_tol_energy=args.energy_tolerance,
        conv_tol_grad=args.gradient_tolerance,
        output=args.output,
        output_qvf=False,
        write_molden_file=False,
        write_population_file=False,
        write_xyz_file=False,
        write_xsf_structure_file=False,
        write_cif_file=False,
    )
    z = np.linspace(-15.0, 20.0, 351)
    profile = None
    if not args.wet:
        from vibeqc.solvation.slab import slab_solute_plane_potential

        lattice = v.LatticeSumOptions()
        lattice.cutoff_bohr = args.cutoff
        lattice.pair_complete_1e = True
        potential = slab_solute_plane_potential(
            system, basis, lattice, z, result.density
        )
        profile = dict(
            z_bohr=z, solute=potential, reaction=np.zeros_like(z), total=potential
        )
    write_slab_result(
        args.output, result, plane_z=z, dry_profile=profile, metadata={
            **vars(args),
            "method": "RKS",
            "functional": "pbe",
            "basis": args.basis,
            "charge": 0,
            "multiplicity": 1,
        },
    )
    if not result.converged:
        raise RuntimeError("Slab electronic calculation did not converge")


if __name__ == "__main__":
    main()
