#!/usr/bin/env python3
"""Convert a VASP POSCAR/CONTCAR to the PIMD structure.dat EXTXYZ format.

No third-party Python packages are required.

Default usage:
    poscar2extxyz
    poscar2extxyz POSCAR
    poscar2extxyz POSCAR -o structure.dat

The output is standard EXTXYZ:
    N
    Lattice="ax ay az bx by bz cx cy cz" Properties=species:S:1:pos:R:3 pbc="T T T"
    Species x y z
    ...

Messages are written to stderr, so stdout remains usable for diagnostics/pipes.
"""

from __future__ import annotations

import argparse
import math
import os
import re
import sys
from pathlib import Path
from typing import Iterable, List, Sequence, Tuple

Vec3 = Tuple[float, float, float]
Mat3 = Tuple[Vec3, Vec3, Vec3]

# Chemical symbols, used only to normalize common VASP labels such as Fe_pv.
ELEMENTS = {
    'H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl','Ar',
    'K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr',
    'Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I','Xe',
    'Cs','Ba','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu',
    'Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac',
    'Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr','Rf','Db','Sg','Bh',
    'Hs','Mt','Ds','Rg','Cn','Nh','Fl','Mc','Lv','Ts','Og'
}


def info(msg: str) -> None:
    print(f"[poscar2extxyz] {msg}", file=sys.stderr)


def warn(msg: str) -> None:
    print(f"[poscar2extxyz] WARNING: {msg}", file=sys.stderr)


def die(msg: str, code: int = 2) -> "None":
    print(f"[poscar2extxyz] ERROR: {msg}", file=sys.stderr)
    raise SystemExit(code)


def clean_line(line: str) -> str:
    """Strip whitespace and common inline comments.

    '#' and '!' are not part of the structural POSCAR grammar and are commonly
    used as human comments in hand-written files.
    """
    s = line.strip()
    for marker in ('#', '!'):
        if marker in s:
            s = s.split(marker, 1)[0].rstrip()
    return s


def ffloat(token: str) -> float:
    """Parse normal or Fortran D-exponent floating-point text."""
    try:
        return float(token.replace('D', 'E').replace('d', 'e'))
    except ValueError as exc:
        raise ValueError(f"not a number: {token!r}") from exc


def parse_three_floats(line: str, what: str) -> Vec3:
    toks = clean_line(line).split()
    if len(toks) < 3:
        raise ValueError(f"{what}: expected at least 3 numbers, got {line.rstrip()!r}")
    try:
        return (ffloat(toks[0]), ffloat(toks[1]), ffloat(toks[2]))
    except ValueError as exc:
        raise ValueError(f"{what}: {exc}") from exc


def det3(m: Mat3) -> float:
    # m is stored as three row-like vectors a,b,c; determinant is invariant to
    # this naming convention and equals a . (b x c).
    a, b, c = m
    return (
        a[0] * (b[1] * c[2] - b[2] * c[1])
        - a[1] * (b[0] * c[2] - b[2] * c[0])
        + a[2] * (b[0] * c[1] - b[1] * c[0])
    )


def scale_vec_components(v: Vec3, s: Vec3) -> Vec3:
    return (v[0] * s[0], v[1] * s[1], v[2] * s[2])


def scale_vec(v: Vec3, s: float) -> Vec3:
    return (v[0] * s, v[1] * s, v[2] * s)


def frac_to_cart(q: Vec3, lattice: Mat3) -> Vec3:
    # POSCAR and EXTXYZ both list lattice vectors as a, b, c.
    a, b, c = lattice
    return (
        q[0] * a[0] + q[1] * b[0] + q[2] * c[0],
        q[0] * a[1] + q[1] * b[1] + q[2] * c[1],
        q[0] * a[2] + q[1] * b[2] + q[2] * c[2],
    )


def canonical_element(label: str) -> Tuple[str, bool]:
    """Return a likely chemical symbol and whether normalization occurred."""
    raw = label.strip()
    if raw in ELEMENTS:
        return raw, False

    # First try conventional capitalization of the whole token.
    if raw:
        cap = raw[0].upper() + raw[1:].lower()
        if cap in ELEMENTS:
            return cap, cap != raw

    # VASP/POTCAR labels often look like Fe_pv, Li_sv, C_h, etc.
    m = re.match(r"^([A-Za-z]{1,2})", raw)
    if m:
        p = m.group(1)
        candidates = []
        if len(p) == 2:
            candidates.append(p[0].upper() + p[1].lower())
        candidates.append(p[0].upper())
        for c in candidates:
            if c in ELEMENTS:
                return c, c != raw

    return raw, False


def parse_potcar_species(path: Path) -> List[str]:
    """Extract one chemical symbol per POTCAR dataset.

    Prefer VRHFIN, which directly identifies the element. Fall back to TITEL.
    """
    if not path.is_file():
        raise FileNotFoundError(str(path))

    text = path.read_text(errors='replace').splitlines()
    vrhfin: List[str] = []
    titel: List[str] = []

    for line in text:
        if 'VRHFIN' in line and '=' in line:
            rhs = line.split('=', 1)[1].strip()
            token = rhs.split(':', 1)[0].strip().split()[0] if rhs else ''
            if token:
                elem, _ = canonical_element(token)
                vrhfin.append(elem)
        elif re.search(r"\bTITEL\s*=", line):
            rhs = line.split('=', 1)[1].strip()
            toks = rhs.split()
            # Typical examples: PAW_PBE Fe_pv 06Sep2000; PAW LDA O 08Apr2002.
            label = ''
            for tok in toks:
                u = tok.upper()
                # Method/family tags are not potential labels.
                if ('PAW' in u or u in {'PBE', 'LDA', 'GGA', 'GW'}
                        or re.fullmatch(r'\d{1,2}[A-Z][a-z]{2}\d{4}', tok)):
                    continue
                elem, changed = canonical_element(tok)
                if elem in ELEMENTS and (changed or tok in ELEMENTS):
                    label = elem
                    break
            if label:
                titel.append(label)

    if vrhfin:
        return vrhfin
    if titel:
        return titel
    raise ValueError(f"could not identify species from POTCAR: {path}")


class Cursor:
    def __init__(self, lines: Sequence[str]):
        self.lines = lines
        self.i = 0

    def next_raw(self, what: str) -> str:
        if self.i >= len(self.lines):
            raise ValueError(f"unexpected end of file while reading {what}")
        line = self.lines[self.i]
        self.i += 1
        return line.rstrip('\n')

    def next_nonempty(self, what: str) -> str:
        while self.i < len(self.lines):
            line = self.next_raw(what)
            if clean_line(line):
                return line
        raise ValueError(f"unexpected end of file while reading {what}")


class PoscarData:
    def __init__(
        self,
        comment: str,
        lattice: Mat3,
        species: List[str],
        counts: List[int],
        positions: List[Vec3],
        coordinate_mode: str,
        selective: bool,
        scale_description: str,
        species_source: str,
    ) -> None:
        self.comment = comment
        self.lattice = lattice
        self.species = species
        self.counts = counts
        self.positions = positions
        self.coordinate_mode = coordinate_mode
        self.selective = selective
        self.scale_description = scale_description
        self.species_source = species_source


def is_int_token(tok: str) -> bool:
    return re.fullmatch(r"[+-]?\d+", tok) is not None


def parse_poscar(path: Path, forced_species: Sequence[str] | None, potcar: Path | None) -> PoscarData:
    try:
        lines = path.read_text(errors='replace').splitlines()
    except OSError as exc:
        raise ValueError(f"cannot read {path}: {exc}") from exc
    if len(lines) < 7:
        raise ValueError("file is too short to be a POSCAR/CONTCAR")

    cur = Cursor(lines)
    comment = cur.next_raw("comment line").strip()

    scale_line = cur.next_nonempty("scaling factor")
    scale_tokens = clean_line(scale_line).split()
    if len(scale_tokens) not in (1, 3):
        raise ValueError(
            "scaling-factor line must contain 1 or 3 numbers; "
            f"got {len(scale_tokens)}: {scale_line!r}"
        )
    try:
        scales = tuple(ffloat(t) for t in scale_tokens)
    except ValueError as exc:
        raise ValueError(f"invalid scaling factor: {exc}") from exc

    raw_lattice: Mat3 = (
        parse_three_floats(cur.next_nonempty("lattice vector a"), "lattice vector a"),
        parse_three_floats(cur.next_nonempty("lattice vector b"), "lattice vector b"),
        parse_three_floats(cur.next_nonempty("lattice vector c"), "lattice vector c"),
    )

    # Resolve VASP scaling semantics.
    if len(scales) == 1:
        s0 = scales[0]
        if s0 == 0.0:
            raise ValueError("universal scaling factor must not be zero")
        if s0 > 0.0:
            scalar = s0
            scale_xyz: Vec3 = (scalar, scalar, scalar)
            lattice = tuple(scale_vec(v, scalar) for v in raw_lattice)  # type: ignore[assignment]
            scale_description = f"universal scale = {scalar:g}"
        else:
            raw_volume = abs(det3(raw_lattice))
            if raw_volume <= 1.0e-30:
                raise ValueError("cannot apply negative volume scaling to a singular lattice")
            target_volume = -s0
            scalar = (target_volume / raw_volume) ** (1.0 / 3.0)
            scale_xyz = (scalar, scalar, scalar)
            lattice = tuple(scale_vec(v, scalar) for v in raw_lattice)  # type: ignore[assignment]
            scale_description = (
                f"target volume = {target_volume:g} A^3 "
                f"(derived scale = {scalar:.12g})"
            )
    else:
        sx, sy, sz = scales
        if sx <= 0.0 or sy <= 0.0 or sz <= 0.0:
            raise ValueError("all three component scaling factors must be positive")
        scale_xyz = (sx, sy, sz)
        lattice = tuple(scale_vec_components(v, scale_xyz) for v in raw_lattice)  # type: ignore[assignment]
        scale_description = f"component scales = ({sx:g}, {sy:g}, {sz:g})"

    volume = abs(det3(lattice))
    if volume <= 1.0e-20:
        raise ValueError("scaled lattice is singular or has essentially zero volume")

    # Species-name line is optional. The next nonempty line is either names or counts.
    line = cur.next_nonempty("species names or atom counts")
    toks = clean_line(line).split()
    if not toks:
        raise ValueError("empty species/count line")

    poscar_species: List[str] | None
    if all(is_int_token(t) for t in toks):
        poscar_species = None
        counts_tokens = toks
    else:
        poscar_species = toks
        counts_line = cur.next_nonempty("atom counts")
        counts_tokens = clean_line(counts_line).split()
        if not counts_tokens or not all(is_int_token(t) for t in counts_tokens):
            raise ValueError(f"invalid atom-count line: {counts_line!r}")

    counts = [int(t) for t in counts_tokens]
    if any(n < 0 for n in counts):
        raise ValueError("atom counts must be non-negative")
    if not counts or sum(counts) <= 0:
        raise ValueError("POSCAR contains no atoms")
    ntypes = len(counts)

    # Resolve species. Explicit --species takes priority for old VASP4 files, but
    # for a named POSCAR we use its own species unless the user explicitly overrides.
    if forced_species:
        if len(forced_species) != ntypes:
            raise ValueError(
                f"--species supplied {len(forced_species)} names but POSCAR has {ntypes} species groups"
            )
        species = list(forced_species)
        species_source = "command line (--species)"
    elif poscar_species is not None:
        if len(poscar_species) != ntypes:
            raise ValueError(
                f"species-name line has {len(poscar_species)} names but count line has {ntypes} groups"
            )
        species = poscar_species
        species_source = "POSCAR species line"
    else:
        if potcar is None:
            auto = path.with_name('POTCAR')
            potcar = auto if auto.is_file() else None
        if potcar is None:
            raise ValueError(
                "this is a VASP4-style POSCAR without species names; "
                "provide --species (e.g. --species Pt H) or place POTCAR beside the POSCAR"
            )
        species = parse_potcar_species(potcar)
        if len(species) != ntypes:
            raise ValueError(
                f"POTCAR provides {len(species)} species but POSCAR has {ntypes} species groups"
            )
        species_source = f"POTCAR ({potcar})"

    normalized: List[str] = []
    for s in species:
        e, changed = canonical_element(s)
        if e not in ELEMENTS:
            raise ValueError(
                f"species label {s!r} cannot be converted to a chemical element symbol; "
                "use --species with standard symbols"
            )
        if changed:
            warn(f"normalizing species label {s!r} -> {e!r}")
        normalized.append(e)
    species = normalized

    # Optional Selective dynamics line.
    mode_line = cur.next_nonempty("coordinate mode or Selective dynamics")
    selective = clean_line(mode_line).lower().startswith('s')
    if selective:
        mode_line = cur.next_nonempty("coordinate mode")

    mode_text = clean_line(mode_line)
    if not mode_text:
        raise ValueError("missing coordinate mode")
    first = mode_text[0]
    cartesian = first in ('C', 'c', 'K', 'k')
    coordinate_mode = "Cartesian" if cartesian else "Direct"

    natom = sum(counts)
    raw_positions: List[Vec3] = []
    for ia in range(natom):
        line = cur.next_nonempty(f"position of atom {ia + 1}/{natom}")
        try:
            q = parse_three_floats(line, f"position of atom {ia + 1}")
        except ValueError as exc:
            raise ValueError(str(exc)) from exc
        raw_positions.append(q)

    positions: List[Vec3] = []
    if cartesian:
        # VASP applies the universal or component-wise scale to Cartesian positions.
        for q in raw_positions:
            positions.append(scale_vec_components(q, scale_xyz))
    else:
        for q in raw_positions:
            positions.append(frac_to_cart(q, lattice))

    return PoscarData(
        comment=comment,
        lattice=lattice,
        species=species,
        counts=counts,
        positions=positions,
        coordinate_mode=coordinate_mode,
        selective=selective,
        scale_description=scale_description,
        species_source=species_source,
    )


def expanded_species(species: Sequence[str], counts: Sequence[int]) -> List[str]:
    out: List[str] = []
    for s, n in zip(species, counts):
        out.extend([s] * n)
    return out


def fmt(x: float) -> str:
    # 16 significant digits is ample for POSCAR -> double-precision conversion.
    if abs(x) < 5.0e-16:
        x = 0.0
    return f"{x:.16g}"


def extxyz_text(data: PoscarData) -> str:
    a, b, c = data.lattice
    lattice_vals = (*a, *b, *c)  # standard EXTXYZ: a, then b, then c
    header = (
        'Lattice="' + ' '.join(fmt(x) for x in lattice_vals) + '" '
        'Properties=species:S:1:pos:R:3 pbc="T T T"'
    )
    labels = expanded_species(data.species, data.counts)
    if len(labels) != len(data.positions):
        raise RuntimeError("internal atom-count mismatch")
    rows = [str(len(labels)), header]
    for s, r in zip(labels, data.positions):
        rows.append(f"{s:<2s}  {fmt(r[0]):>20s}  {fmt(r[1]):>20s}  {fmt(r[2]):>20s}")
    return '\n'.join(rows) + '\n'


def parse_args(argv: Sequence[str]) -> argparse.Namespace:
    p = argparse.ArgumentParser(
        prog='poscar2extxyz',
        description='Convert VASP POSCAR/CONTCAR to PIMD structure.dat (standard EXTXYZ).',
    )
    p.add_argument(
        'input', nargs='?', default='POSCAR',
        help='input POSCAR/CONTCAR file (default: POSCAR)'
    )
    p.add_argument(
        '-o', '--output', default='structure.dat',
        help='output EXTXYZ file (default: structure.dat; use - for stdout)'
    )
    p.add_argument(
        '--species', nargs='+', metavar='EL',
        help='species symbols in POSCAR group order; useful for VASP4 files'
    )
    p.add_argument(
        '--potcar',
        help='POTCAR used to determine species for a VASP4-style POSCAR; default: POTCAR beside input'
    )
    p.add_argument(
        '-q', '--quiet', action='store_true',
        help='suppress informational messages (errors and warnings remain)'
    )
    return p.parse_args(argv)


def main(argv: Sequence[str] | None = None) -> int:
    args = parse_args(sys.argv[1:] if argv is None else argv)
    inpath = Path(args.input)
    potcar = Path(args.potcar) if args.potcar else None

    try:
        data = parse_poscar(inpath, args.species, potcar)
        text = extxyz_text(data)
    except (ValueError, OSError) as exc:
        die(str(exc))

    natom = sum(data.counts)
    if not args.quiet:
        info(f"input        : {inpath}")
        info(f"comment      : {data.comment or '(blank)'}")
        info(f"species      : {' '.join(data.species)}  ({data.species_source})")
        info(f"atom counts  : {' '.join(str(n) for n in data.counts)}  [total {natom}]")
        info(f"scale        : {data.scale_description}")
        info(f"coordinates  : {data.coordinate_mode} -> Cartesian Angstrom")
        if data.selective:
            info("selective dyn: present (T/F flags are intentionally not written to PIMD structure.dat)")
        info(f"cell volume  : {abs(det3(data.lattice)):.12g} A^3")
        info("EXTXYZ cell  : standard ordering a_x a_y a_z b_x b_y b_z c_x c_y c_z")

    if args.output == '-':
        sys.stdout.write(text)
        if not args.quiet:
            info("output       : stdout")
    else:
        outpath = Path(args.output)
        if outpath.exists() and not args.quiet:
            warn(f"overwriting existing file: {outpath}")
        try:
            outpath.write_text(text)
        except OSError as exc:
            die(f"cannot write {outpath}: {exc}")
        if not args.quiet:
            info(f"output       : {outpath}")
            info("done         : structure.dat is ready for <iboundary> EXTXYZ")

    return 0


if __name__ == '__main__':
    raise SystemExit(main())
