# -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Any
from .backends import BackendNotAvailableError, dispatch_structure_backend, normalize_backend, to_builtin

def get_available_xray_wavelengths(*, backend: str='pymatgen') -> dict[str, Any]:
    b=normalize_backend(backend); b='pymatgen' if b=='auto' else b
    if b!='pymatgen': raise BackendNotAvailableError(f'backend not implemented: {backend!r}')
    from pymatgen.analysis.diffraction.xrd import WAVELENGTHS
    return {'backend':'pymatgen','wavelengths':{str(k):float(v) for k,v in WAVELENGTHS.items()}}

def _hkl_list(hkl):
    try: return [int(x) for x in hkl]
    except Exception:
        try: return [float(x) for x in hkl]
        except Exception: return list(hkl)

def _peak(pattern, i):
    hkls=pattern.hkls[i]; primary=hkls[0] if hkls else {}; hkl=primary.get('hkl') if isinstance(primary,dict) else None; mul=primary.get('multiplicity') if isinstance(primary,dict) else None
    return {'index':int(i),'two_theta':float(pattern.x[i]),'intensity':float(pattern.y[i]),'d_hkl':float(pattern.d_hkls[i]),
            'hkl':_hkl_list(hkl) if hkl is not None else None,'multiplicity':int(mul) if mul is not None else None,'hkls':to_builtin(hkls)}

def get_xrd_inf(structure: Any, *, backend: str='auto', wavelength: str|float='CuKa1', two_theta_range=(10.0,80.0), symprec: float=0.0, max_peaks: int|None=None) -> dict[str, Any]:
    b=dispatch_structure_backend(structure, backend)
    if b!='pymatgen': raise RuntimeError(f'unsupported backend {b!r}')
    from pymatgen.analysis.diffraction.xrd import XRDCalculator, WAVELENGTHS
    try: wl_value=float(wavelength)
    except Exception: wl_value=float(WAVELENGTHS[str(wavelength)]) if str(wavelength) in WAVELENGTHS else None
    tmin,tmax=float(two_theta_range[0]),float(two_theta_range[1]); calc=XRDCalculator(wavelength=wavelength,symprec=float(symprec)); pat=calc.get_pattern(structure,two_theta_range=(tmin,tmax))
    n=len(pat.x); nret=n if max_peaks is None else min(n,int(max_peaks))
    return {'backend':'pymatgen','calculator':'XRDCalculator','wavelength':wavelength,'wavelength_angstrom':wl_value,
            'two_theta_range':[tmin,tmax],'symprec':float(symprec),'n_peaks':n,'n_returned_peaks':nret,
            'peaks':[_peak(pat,i) for i in range(nret)]}
