"""
(Mostly deprecated) code to handle coordinate systems and transform
between them.

Basically all of this should be taken over by stc and astropy
"""

#c Copyright 2008-2025, the GAVO project <gavo@ari.uni-heidelberg.de>
#c
#c This program is free software, covered by the GNU GPL.  See the
#c COPYING file in the source distribution.


import math
import types
from math import sin, cos, pi #noflake: exported names
import re

import numpy
from numpy import linalg

from gavo import utils
from gavo.base.unitconv import computeConversionFactor
from gavo.utils import DEG
from gavo.utils import pgsphere
from gavo.utils import pyfits

from gavo.utils.dachstypes import (Any, Callable, Dict, List, NDArray,
	Numeric, Optional, Sequence, TYPE_CHECKING, Tuple, Union)

wcs = utils.DeferredImport("wcs", "from astropy import wcs")
if TYPE_CHECKING:
	from astropy.wcs import WCS # type: ignore


fitsKwPat = re.compile("[A-Z0-9_-]{1,8}$")

def makePyfitsFromDict(d: Dict[str, Any]) -> pyfits.Header:
	"""returns a pyfits header with the cards of d.items().

	Only keys "looking like" FITS header keywords are used, i.e. all-uppercase
	and shorter than 9 characters.
	"""
	res = pyfits.Header()
	res.update(dict((str(key), val)
		for key, val in d.items()
		if fitsKwPat.match(key) and val is not None))
	return res


_wcsTestDict = {
	"CRVAL1": 0,   "CRVAL2": 0, "CRPIX1": 50,  "CRPIX2": 50,
	"CD1_1": 0.01, "CD1_2": 0, "CD2_1": 0,    "CD2_2": 0.01,
	"NAXIS1": 100, "NAXIS2": 100, "CUNIT1": "deg", "CUNIT2": "deg",
	"CTYPE1": 'RA---TAN-SIP', "CTYPE2": 'DEC--TAN-SIP', "LONPOLE": 180.,
}


class Box(object):
	"""A 2D box.

	It can be constructed either with two tuples, giving two points
	delimiting the box, or with four arguments x0, x1, y0, y1.

	To access the thing, you can either access the x[01], y[01] attributes
	or use getitem to retrieve the upper right and lower left corner.

	The slightly silly ordering of the bounding points (larger values
	first) is for consistency with Postgresql.
	"""
	def __init__(self,
			x0: Union[Tuple[float, float], float],
			x1: Union[Tuple[float, float], float],
			y0: Optional[float] = None,
			y1: Optional[float] = None) -> None:
		if y0 is None: # explaining the signature to mypy is not worth it.
			x0, y0 = x0  #type: ignore
			x1, y1 = x1  #type: ignore
		lowerLeft: _2DPoint = (min(x0, x1), min(y0, y1)) # type: ignore
		upperRight: _2DPoint = (max(x0, x1), max(y0, y1)) # type: ignore
		self.x0: float = float(upperRight[0])
		self.y0: float = float(upperRight[1])
		self.x1: float = float(lowerLeft[0])
		self.y1: float = float(lowerLeft[1])
	
	def __getitem__(self, index: int) -> Tuple[float, float]:
		if index==0 or index==-2:
			return (self.x0, self.y0)
		elif index==1 or index==-1:
			return (self.x1, self.y1)
		else:
			raise IndexError("len(box) is always 2")

	def __str__(self) -> str:
		return "((%.4g,%.4g), (%.4g,%.4g))"%(self.x0, self.y0, self.x1, self.y1)

	def __repr__(self) -> str:
		return "Box((%g,%g), (%g,%g))"%(self.x0, self.y0, self.x1, self.y1)


def getBbox(points: List[Tuple[float, float]]) -> Box:
	"""returns a bounding box for the sequence of 2-sequences points.

	The thing returned is a coords.Box.

	>>> getBbox([(0.25, 1), (-3.75, 1), (-2, 4)])
	Box((0.25,4), (-3.75,1))
	"""
	xCoos, yCoos = [[p[i] for p in points] for i in range(2)]
	return Box(min(xCoos), max(xCoos), min(yCoos), max(yCoos))


def clampAlpha(alpha: float) -> float:
	while alpha>360:
		alpha -= 360
	while alpha<0:
		alpha += 360
	return alpha


def clampDelta(delta: float) -> float:
	return max(-90, min(90, delta))


def straddlesStitchingLine(minRA: Numeric, maxRA: Numeric) -> bool:
	"""returns true if something bordered by minRA and maxRA presumably straddles
	the stitching line.

	This assumes minRA<maxRA, and that "something" is less than 180 degrees in
	longitude.

	Angles are in degrees here.
	"""
	return float(maxRA)>270 and float(minRA)<90


def _calcFootprintMonkeypatch(
		self: "WCS",
		hdr: Optional[pyfits.Header] = None,
		undistort: bool = True) -> NDArray:
	"""returns the coordinates of the four corners of an image.

	This is for monkeypatching astropy.wcs. pywcs, at least up to 1.11 did
	really badly when non-spatial coordinates are present.  TODO: see
	if there's astropy code that does this better.
	
	This method relies on the _monkey_naxis_lengths attribute left by getWCS to
	figure out the axis lengths.

	pywcs' hdr argument is always ignored here.
	"""
	naxis1, naxis2 = self._monkey_naxis_lengths
	corners = [[1,1],[1,naxis2], [naxis1,naxis2], [naxis1, 1]]

	# we want our polygons to have a counterclockwise winding direction,
	# and until I think about this a bit more deeply or get a sufficiently
	# capable library, I just revert my sense if the determinant of the
	# CD matrix is negative.  That's gut feeling, not proven right.
	if linalg.det(self.pixel_scale_matrix)<0:
		corners.reverse()

	if undistort:
		return self.all_pix2world(corners, 1)*self.toDegVec
	else:
		return self.wcs_pix2world(corners, 1)*self.toDegVec


def _monkeypatchWCS(
		wcsObj: "WCS",
		naxis: Sequence[int],
		wcsFields: pyfits.Header) -> None:
	"""monkeypatches wcs.WCS instances for DaCHS' purposes.
	"""
	wcsObj._dachs_header = wcsFields
	wcsObj.longAxis = naxis[0]
	if len(naxis)>1:
		wcsObj.latAxis = naxis[1]
	wcsObj._monkey_naxis_lengths = [wcsFields.get("NAXIS%d"%i)
		for i in naxis]
	wcsObj.toDegVec = numpy.array([
		computeConversionFactor(wcsFields.get(f"CUNIT{naxis[1]}", "deg"), "deg"),
		computeConversionFactor(wcsFields.get(f"CUNIT{naxis[0]}", "deg"), "deg")])
	wcsObj.calcFootprint = types.MethodType(
		_calcFootprintMonkeypatch, wcsObj)


_PerhapsWCS = Union[Dict[str, Any], "WCS"]
_2DPoint = Tuple[Numeric, Numeric]

def getWCS(
		wcsFields: _PerhapsWCS,
		naxis: Sequence[int] = (1,2),
		relax: bool = True) -> "WCS":
	"""returns a WCS instance from wcsFields
	
	wcsFields can be either a dictionary or a pyfits header giving
	some kind of WCS information, or an wcs.WCS instance that is
	returned verbatim.

	This will return None if no (usable) WCS information is found in the header.

	We monkeypatch the resulting WCS structure quite a bit.  Among
	others:

	* there's longAxis and latAxis attributes taken from naxis
	* there's _dachs_header, containing the incoming k-v pairs
	* there's _monkey_naxis_length, the lengths along the WCS axes.
	"""
	if isinstance(wcsFields, wcs.WCS):
		return wcsFields
	if isinstance(wcsFields, dict):
		wcsFields = makePyfitsFromDict(wcsFields)

	# pywcs used to invent identity transforms if no WCS keys are present.
	# Hence. we do some sanity checking up front to weed those out.
	if ("CD1_1" not in wcsFields
			and "CDELT1" not in wcsFields
			and "PC1_1" not in wcsFields
			and "CNPIX1" not in wcsFields):
		return None
	
	# workaround for a bug in pywcs 1.11: .*_ORDER=0 must not happen
	for key in ["AP_ORDER", "BP_ORDER", "A_ORDER", "B_ORDER"]:
		if wcsFields.get(key)==0:
			del wcsFields[key]

	# wcslib (at least in 5.16) wants to do DSS corrections if they see
	# either XPIXELSZ and YPIXELSZ; hide them, because that almost
	# never works.
	for key in ["XPIXELSZ", "YPIXELSZ"]:
		if key in wcsFields:
			del wcsFields[key]

	wcsObj = wcs.WCS(wcsFields, relax=relax, naxis=naxis)
	_monkeypatchWCS(wcsObj, naxis, wcsFields)

	return wcsObj


def pix2foc(wcsFields: _PerhapsWCS, pixels: _2DPoint
		) -> _2DPoint:
	"""returns the focal plane coordinates for the 2-sequence pixels.

	(this is a thin wrapper intended to abstract for pix2world's funky
	calling convention; also, we fix on the silly "0 pixel is 1 convention")
	"""
	wcsObj = getWCS(wcsFields)
	val = wcsObj.pix2foc((pixels[0],), (pixels[1],), 1)
	return val[0][0], val[1][0]


def pix2sky(
		wcsFields: _PerhapsWCS,
		pixels: _2DPoint) -> _2DPoint:
	"""returns the sky coordinates for the 2-sequence pixels.

	(this is a thin wrapper intended to abstract for pix2world's funky
	calling convention; also, we fix on the silly "0 pixel is 1 convention")
	"""
	wcsObj = getWCS(wcsFields)
	val = wcsObj.all_pix2world((pixels[0],), (pixels[1],), 1)*wcsObj.toDegVec
	return val[0][0], val[1][0]


def sky2pix(
		wcsFields: _PerhapsWCS,
		longLat: _2DPoint) -> _2DPoint:
	"""returns the pixel coordinates for the 2-sequence longLad.

	(this is a thin wrapper intended to abstract for world2pix's funky
	calling convention; also, we fix on the silly "0 pixel is 1 convention")
	lonLat is supposed to be in degrees regardless of the units of the
	WCS.
	"""
	wcs = getWCS(wcsFields)
	val = wcs.wcs_world2pix(
		(longLat[0]/wcs.toDegVec[0],), (longLat[1]/wcs.toDegVec[1],), 1)
	return val[0][0], val[1][0]


def getPixelSizeDeg(wcsFields: _PerhapsWCS) -> _2DPoint:
	"""returns the sizes of a pixel at roughly the center of the image for
	wcsFields.

	Near the pole, this gets a bit weird; we do some limitation of the width
	of RA pixels there.
	"""
	wcs = getWCS(wcsFields)
	width, height = wcs._dachs_header["NAXIS1"], wcs._dachs_header["NAXIS2"]
	cosDelta = max(0.01, math.cos(pix2sky(wcs, (width/2, height/2))[1]*DEG))

	p0 = pix2sky(wcs, (width/2, height/2))
	p1 = pix2sky(wcs, (width/2+1, height/2))
	p2 = pix2sky(wcs, (width/2, height/2+1))
	return abs(float(p1[0]-p0[0]))*cosDelta, abs(float(p2[1]-p0[1]))


def getWCSTrafo(wcsFields: _PerhapsWCS
		) -> Callable[[Numeric, Numeric], Tuple[Numeric, Numeric]]:
	"""returns a callable transforming pixel to physical coordinates.

	wcsFields is passed to getWCS, see there for legal types.
	"""
	wcs = getWCS(wcsFields)
	return lambda x, y: pix2sky(wcs, (x, y))


def getInvWCSTrafo(wcsFields: _PerhapsWCS
		) -> Callable[[Numeric, Numeric], Tuple[Numeric, Numeric]]:
	"""returns a callable transforming physical to pixel coordinates.

	wcsFields is passed to getWCS, see there for legal types.
	"""
	wcs = getWCS(wcsFields)
	return lambda ra, dec: sky2pix(wcs, (ra,dec))


def getSpolyFromWCSFields(wcsFields: _PerhapsWCS) -> pgsphere.SPoly:
	"""returns a pgsphere spoly corresponding to wcsFields

	wcsFields is passed to getWCS, see there for legal types.

	The polygon returned is computed by using the four corner points
	assuming a rectangular image.  This typically is only loosely related
	to a proper spherical polygon describing the shape, as image boundaries
	in the usual projects are not great circles.

	Also, the spoly will be in the coordinate system of the WCS.  If that
	is not ICRS, you'll probably get something incompatible with most of the
	VO.
	"""
	wcs = getWCS(wcsFields)
	return pgsphere.SPoly([pgsphere.SPoint.fromDegrees(*p) # type: ignore
			for p in wcs.calcFootprint(wcs._dachs_header)])


def getCenterFromWCSFields(
		wcsFields: _PerhapsWCS,
		spatialAxes: Tuple[int, int] = (1,2)) -> _2DPoint:
	"""returns RA and Dec of the center of an image described by wcsFields.

	This will use the 1-based axes given by spatialAxes to figure out
	the pixel lengths of the axes.
	"""
	wcs = getWCS(wcsFields)
	if wcs is None:
		raise ValueError("No WCS solution found")

	center1 = wcs._dachs_header["NAXIS%s"%spatialAxes[0]]/2.
	center2 = wcs._dachs_header["NAXIS%s"%spatialAxes[1]]/2.
	return pix2sky(wcs, (center1, center2))


def getCoveringCircle(
		wcsFields: _PerhapsWCS,
		spatialAxes: Sequence[int] = (1,2)
		) -> Optional[pgsphere.SCircle]:
	"""returns a pgsphere.scircle large enough to cover the image
	described by wcsFields.
	"""
	wcs = getWCS(wcsFields)
	center = getCenterFromWCSFields(wcs)

	height, width = (wcs._dachs_header["NAXIS%s"%spatialAxes[0]],
		wcs._dachs_header["NAXIS%s"%spatialAxes[1]])
	radius = max(
			getGCDist(center, pix2sky(wcs, corner))
		for corner in [(0, 0), (height, 0), (0, width), (height, width)])

	centerPoint = pgsphere.SPoint.fromDegrees(*center)
	if centerPoint is None:
		return None
	else:
		return pgsphere.SCircle(centerPoint, radius*DEG)


def getSkyWCS(hdr: _PerhapsWCS) -> Tuple["WCS", List[int]]:
	"""returns a pair of a wcs.WCS instance and a sequence of
	the spatial axis indexes.

	This will be None, () if no WCS could be discerned.  There's some
	heuristics involved in the identification of the spatial coordinates
	that will probably fail for unconventional datasets.
	"""
	wcsAxes = []
	# heuristics: iterate through CTYPEn, anything that's got
	# a - is supposed to be a position (needs some refinement :-)
	for ind in range(1, hdr["NAXIS"]+1):
		if "-" in hdr.get("CTYPE%s"%ind, ""):
			wcsAxes.append(ind)

	if not wcsAxes:
		# more heuristics to be inserted here
		return None, []

	if len(wcsAxes)!=2:
		raise utils.ValidationError("This FITS has !=2"
			" spatial WCS axes.  Please contact the DaCHS authors and"
			" make them support it.", "PUBDID")

	return getWCS(hdr, naxis=wcsAxes), wcsAxes


def getPixelLimits(cooPairs: List[_2DPoint], wcsFields: "WCS"
		) -> List[Tuple[int, Numeric, Numeric]]:
	"""returns pixel cutout slices for covering cooPairs in an image with
	wcsFields.

	cooPairs is a sequence of (ra, dec) tuples.  wcsFields is a DaCHS-enhanced
	wcs.WCS instance.

	Behaviour if cooPairs use a different coordinate system from wcsFields
	is undefined at this point.

	Each cutout slice is a tuple of (FITS axis number, lower limit, upper limit).

	If cooPairs is off the wcsFields coverage, a null cutout on the longAxis
	is returned.
	"""
	latAxis = int(wcsFields.latAxis)
	longAxis = int(wcsFields.longAxis)
	latPixels = wcsFields._dachs_header["NAXIS%d"%latAxis]
	longPixels = wcsFields._dachs_header["NAXIS%d"%longAxis]

	# pywcs used to do really funny things when we "wrap around".  Therefore, we
	# clamp values to be within the pywcs-safe region.  Note that
	# due to spherical magic this is not enough to ensure +/-Inf behaviour
	# for SODA; TODO: re-evaluate this for astropy.wcs at some point.
	cooPairs = [(
			min(359.99999, max(-89.9999, ra)), # type: ignore
			min(89.9999, max(-89.9999, dec))) # type: ignore
		for ra, dec in cooPairs]
	
	# no, I will not try to understand why mypy is confused by the min()s

	slices: List[Tuple[int, Numeric, Numeric]] = []
	pixelFootprint = numpy.asarray(
		numpy.round(wcsFields.wcs_world2pix(cooPairs, 1)), numpy.int32)
	pixelLimits = [
		(min(pixelFootprint[:,0]), max(pixelFootprint[:,0])), # type: ignore
		(min(pixelFootprint[:,1]), max(pixelFootprint[:,1]))] # type: ignore
	
	# see if we're completely off coverage
	if pixelLimits[0][1]<0 or pixelLimits[1][1]<0:
		return [(longAxis, 0, 0)]
	if pixelLimits[0][0]>longPixels or pixelLimits[1][0]>latPixels:
		return [(longAxis, 0, 0)]

	# now crop to the actual pixel values
	pixelLimits = [
		(max(pixelLimits[0][0], 1), min(pixelLimits[0][1], longPixels)), # type: ignore
		(max(pixelLimits[1][0], 1), min(pixelLimits[1][1], latPixels))]  # type: ignore

	if pixelLimits[0]!=(1, longPixels):
		slices.append((longAxis,)+pixelLimits[0])
	if pixelLimits[1]!=(1, latPixels):
		slices.append((latAxis,)+pixelLimits[1])
	return slices


def sgn(a: Numeric) -> int:
	if a<0:
		return -1
	elif a>0:
		return 1
	else:
		return 0


def dirVecToCelCoos(dirVec: NDArray) -> _2DPoint:
	"""returns alpha, delta in degrees for the direction vector dirVec.

	>>> utils.nprepr(dirVecToCelCoos(utils.spherToCart(25.25*DEG, 12.125*DEG)))
	'[25.25 12.12]'
	>>> utils.nprepr(dirVecToCelCoos(utils.spherToCart(25.25*DEG, 12.125*DEG)*16))
	'[25.25 0.7522]'
	>>> utils.nprepr(dirVecToCelCoos(utils.spherToCart(25.25*DEG, 12.125*DEG)+
	...   utils.spherToCart(30.75*DEG, 20.0*DEG)))
	'[27.95 7.988]'
	"""
	dirVec = dirVec/numpy.inner(dirVec, dirVec)
	alpha = math.atan2(dirVec[1], dirVec[0])
	if alpha<0:
		alpha += 2*math.pi
	return alpha*180./math.pi, math.asin(dirVec[2])*180./math.pi


def getTangentialUnits(cPos: NDArray) -> Tuple[NDArray, NDArray]:
	"""returns the unit vectors for RA and Dec at the unit circle position cPos.

	We compute them by solving u_1*p_1+u_2*p_2=0 (we already know that
	u_3=0) simultaneously with u_1^2+u_2^2=1 for RA, and by computing the
	cross product of the RA unit and the radius vector for dec.

	This becomes degenerate at the poles.  If we're exactly on a pole,
	we *define* the unit vectors as (1,0,0) and (0,1,0).

	Orientation is a pain -- the convention used here is that unit delta
	always points to the pole.

	>>> cPos = utils.spherToCart(45*DEG, -45*DEG)
	>>> ua, ud = getTangentialUnits(cPos)
	>>> print(numpy.dot(ua, ua), numpy.dot(ud, ud))
	1.0 1.0
	>>> utils.nprepr([numpy.dot(cPos, ua), numpy.dot(cPos, ud)])
	'[0 0]'
	>>> utils.nprepr(ua), utils.nprepr(ud)
	('[-0.7071 0.7071 -0]', '[-0.5 -0.5 -0.7071]')
	>>> ua, ud = getTangentialUnits(utils.spherToCart(180*DEG, 60*DEG))
	>>> utils.nprepr(ua), utils.nprepr(ud)
	('[-1.225e-16 -1 -0]', '[0.866 -1.061e-16 0.5]')
	>>> ua, ud = getTangentialUnits(utils.spherToCart(0*DEG, 60*DEG))
	>>> utils.nprepr(ua), utils.nprepr(ud)
	('[-0 1 -0]', '[-0.866 -0 0.5]')
	>>> ua, ud = getTangentialUnits(utils.spherToCart(0, -60*DEG))
	>>> utils.nprepr(ua), utils.nprepr(ud)
	('[-0 1 -0]', '[-0.866 -0 -0.5]')
	"""
	try:
		normalizer = 1/math.sqrt(cPos[0]**2+cPos[1]**2)
	except ZeroDivisionError:
		return numpy.array([1.,0.,0.]), numpy.array([0., 1., 0])
	alphaUnit = normalizer*numpy.array([cPos[1], -cPos[0], 0.])
	deltaUnit = normalizer*numpy.array(
		[cPos[0]*cPos[2], cPos[1]*cPos[2], -cPos[0]**2-cPos[1]**2])

	# now orient the vectors: in delta, we always look towards the pole
	if sgn(cPos[2])!=sgn(deltaUnit[2]):
		deltaUnit = -1*deltaUnit  # TODO this breaks on the equator

	# The orientation of alphaUnit depends on the hemisphere
	if cPos[2]<0:  # south
		if numpy.inner(numpy.cross(deltaUnit, alphaUnit), cPos)<0:
			alphaUnit = -1*alphaUnit

	else:  # north
		if numpy.inner(numpy.cross(deltaUnit, alphaUnit), cPos)>0:
			alphaUnit = -1*alphaUnit

	return alphaUnit, deltaUnit


def movePm(
		alphaDeg: Numeric,
		deltaDeg: Numeric,
		pmAlpha: Numeric,
		pmDelta: Numeric,
		timeDiff: Numeric,
		foreshort: bool = False) -> _2DPoint:
	"""returns alpha and delta for an object with pm pmAlpha after timeDiff.

	pmAlpha has to have cos(delta) applied, everything is supposed to be
	in degrees, the time unit is yours to choose.
	"""
	alpha, delta = alphaDeg/180.*math.pi, deltaDeg/180.*math.pi
	pmAlpha, pmDelta = pmAlpha/180.*math.pi, pmDelta/180.*math.pi
	sd, cd = math.sin(delta), math.cos(delta)
	sa, ca = math.sin(alpha), math.cos(alpha)
	muAbs = math.sqrt(pmAlpha**2+pmDelta**2);
	muTot = muAbs+0.5*foreshort*timeDiff;

	if muAbs<1e-20:
		return alphaDeg, deltaDeg
	# this is according to Mueller, 115 (4.94)
	dirA = pmAlpha/muAbs;
	dirD = pmDelta/muAbs;
	sinMot = sin(muTot*timeDiff);
	cosMot = cos(muTot*timeDiff);

	dirVec = numpy.array([
		-sd*ca*dirD*sinMot - sa*dirA*sinMot + cd*ca*cosMot,
		-sd*sa*dirD*sinMot + ca*dirA*sinMot + cd*sa*cosMot,
		+cd*dirD*sinMot + sd*cosMot])
	return dirVecToCelCoos(dirVec)


def getGCDist(pos1: _2DPoint, pos2: _2DPoint) -> float:
	"""returns the distance along a great circle between two points.

	The distance is in degrees, the input positions are in degrees.
	"""
	scalarprod = numpy.dot(
		utils.spherToCart(pos1[0]*DEG, pos1[1]*DEG),
		utils.spherToCart(pos2[0]*DEG, pos2[1]*DEG))
	# cope with numerical trouble
	if scalarprod>=1:
		return 0
	return math.acos(scalarprod)/DEG


def _test():  # pragma: no cover
	import doctest
	doctest.testmod()


if __name__=="__main__": # pragma: no cover
	_test()
