#!/usr/bin/env python3
"""Experimental 2-D periodic vorticity solver forced only by aircraft winds."""

import math

import numpy as np


SOUTH, NORTH, WEST, EAST = 48.5, 53.9, 3.0, 10.8
METRES_PER_DEGREE = 111320.0
LONGITUDE_SCALE = METRES_PER_DEGREE * math.cos(math.radians(51.2))
NX = NY = 96
PADDING_M = 180000.0
LENGTH_X = (EAST-WEST) * LONGITUDE_SCALE + 2*PADDING_M
LENGTH_Y = (NORTH-SOUTH) * METRES_PER_DEGREE + 2*PADDING_M
SIGMA_M = 35000.0
TAU_S = 120.0
VISCOSITY = 20000.0
DRAG = 1/14400.0
MAX_OBSERVATION_AGE = 120.0
MAX_STEP = 120.0
MIN_AIRCRAFT = 3
MIN_ALT_FT, MAX_ALT_FT = 35000, 38000


class NumericalError(ValueError):
    """The solver state cannot safely be continued."""


class AircraftWindSolver:
    """Evolve a periodic flow, including its separately nudged mean wind."""

    def __init__(self):
        self.dx, self.dy = LENGTH_X/NX, LENGTH_Y/NY
        x, y = np.arange(NX)*self.dx, np.arange(NY)*self.dy
        self.x, self.y = np.meshgrid(x, y)
        kx = 2*np.pi*np.fft.fftfreq(NX, d=self.dx)
        ky = 2*np.pi*np.fft.fftfreq(NY, d=self.dy)
        self.kx, self.ky = np.meshgrid(kx, ky)
        self.k2 = self.kx**2 + self.ky**2
        self.inverse_k2 = np.zeros_like(self.k2)
        np.divide(1, self.k2, out=self.inverse_k2, where=self.k2 != 0)
        self.dealias = ((np.abs(self.kx) <= (2/3)*np.max(np.abs(kx)))
                        & (np.abs(self.ky) <= (2/3)*np.max(np.abs(ky))))
        self.zeta = np.zeros((NY, NX))
        self.mean = np.zeros(2)
        self.last_time = None
        self.latest = {}
        self.time_warning = None

    def update_observations(self, rows, timestamp, now):
        if not math.isfinite(timestamp) or timestamp > now + 2:
            raise ValueError("Invalid observation timestamp")
        for row in rows:
            identity = row["icao"]
            values = [row[name] for name in ("lat", "lon", "east", "north", "alt_ft")]
            if (not isinstance(identity, str) or not identity
                    or not all(isinstance(v, (int, float)) and math.isfinite(v) for v in values)
                    or not SOUTH <= row["lat"] <= NORTH or not WEST <= row["lon"] <= EAST
                    or not MIN_ALT_FT <= row["alt_ft"] <= MAX_ALT_FT
                    or math.hypot(row["east"], row["north"]) > 130):
                raise ValueError("Invalid aircraft observation")
        for row in rows:
            identity = row["icao"]
            previous = self.latest.get(identity)
            if previous is None or timestamp > previous["observed_at"]:
                self.latest[identity] = {**row, "observed_at": timestamp}
        self.latest = {key: value for key, value in self.latest.items()
                       if -2 <= now-value["observed_at"] <= MAX_OBSERVATION_AGE}

    def weights(self):
        items = list(self.latest.values())
        weights = []
        for row in items:
            px = PADDING_M + (row["lon"]-WEST)*LONGITUDE_SCALE
            py = PADDING_M + (row["lat"]-SOUTH)*METRES_PER_DEGREE
            weights.append(np.exp(-((self.x-px)**2+(self.y-py)**2)/(2*SIGMA_M**2)))
        return items, np.array(weights) if weights else np.empty((0, NY, NX))

    def velocity(self, zeta, mean):
        spectral = np.fft.fft2(zeta)
        psi = -spectral * self.inverse_k2
        psi[0, 0] = 0
        u = np.fft.ifft2(-1j*self.ky*psi).real + mean[0]
        v = np.fft.ifft2(1j*self.kx*psi).real + mean[1]
        return u, v

    def tendency(self, zeta, mean, items, weights):
        spectrum = np.fft.fft2(zeta)
        u, v = self.velocity(zeta, mean)
        dx_zeta = np.fft.ifft2(1j*self.kx*spectrum).real
        dy_zeta = np.fft.ifft2(1j*self.ky*spectrum).real
        advection = np.fft.ifft2(np.fft.fft2(u*dx_zeta + v*dy_zeta)*self.dealias).real
        laplace = np.fft.ifft2(-self.k2*spectrum).real
        if items:
            total = weights.sum(axis=0)
            denominator = np.maximum(1, total)
            east = np.array([row["east"] for row in items])[:, None, None]
            north = np.array([row["north"] for row in items])[:, None, None]
            force_u = np.sum(weights*(east-u), axis=0)/(denominator*TAU_S)
            force_v = np.sum(weights*(north-v), axis=0)/(denominator*TAU_S)
        else:
            force_u = np.zeros_like(zeta)
            force_v = np.zeros_like(zeta)
        curl = np.fft.ifft2(1j*self.kx*np.fft.fft2(force_v)
                            - 1j*self.ky*np.fft.fft2(force_u)).real
        return -advection + VISCOSITY*laplace - DRAG*zeta + curl, np.array([
            float(np.mean(force_u)) - DRAG*mean[0],
            float(np.mean(force_v)) - DRAG*mean[1],
        ])

    def step(self, seconds, items, weights):
        if seconds < 0 or seconds > MAX_STEP or not math.isfinite(seconds):
            raise ValueError("Solver time step outside supported 0–120 seconds")
        if not np.isfinite(self.zeta).all() or not np.isfinite(self.mean).all():
            raise NumericalError("Nonfinite solver state")
        u, v = self.velocity(self.zeta, self.mean)
        courant = float(np.max(np.abs(u)))/self.dx + float(np.max(np.abs(v)))/self.dy
        diffusion = VISCOSITY*(1/self.dx**2 + 1/self.dy**2)
        limit = min(10.0, .4/max(courant, 1e-12), .2/max(diffusion, 1e-12))
        count = max(1, math.ceil(seconds/limit))
        dt = seconds/count
        for _ in range(count):
            z1, m1 = self.tendency(self.zeta, self.mean, items, weights)
            z2, m2 = self.tendency(self.zeta+dt*z1/2, self.mean+dt*m1/2, items, weights)
            self.zeta += dt*z2
            self.mean += dt*m2
        if not np.isfinite(self.zeta).all() or not np.isfinite(self.mean).all():
            raise NumericalError("Nonfinite solver state")
        u, v = self.velocity(self.zeta, self.mean)
        if float(np.max(np.hypot(u, v))) > 150:
            raise NumericalError("Solver speed exceeded safety limit")

    def update(self, rows, now, observed_at=None):
        if not math.isfinite(now):
            raise ValueError("Invalid solver timestamp")
        elapsed = None if self.last_time is None else now - self.last_time
        if elapsed is not None and elapsed < 0:
            self.latest.clear()
        self.update_observations(rows, now if observed_at is None else observed_at, now)
        items, weights = self.weights()
        self.time_warning = None
        if self.last_time is None and len(items) >= MIN_AIRCRAFT:
            self.mean = np.mean([[row["east"], row["north"]] for row in items], axis=0)
            self.last_time = now
        elif self.last_time is not None:
            if elapsed < 0:
                self.time_warning = "Systemzeit zurückgesetzt; Modellzeit neu ausgerichtet"
            elif elapsed > MAX_STEP:
                self.step(MAX_STEP, [], np.empty((0, NY, NX)))
                self.time_warning = "Modellpause über 120 s; Integration begrenzt"
            else:
                self.step(elapsed, items, weights)
            self.last_time = now
        return len(items)

    def grid(self, now):
        if self.last_time is None or len(self.latest) < MIN_AIRCRAFT:
            raise ValueError("Warte auf mindestens drei aktuelle Flugzeugwinde")
        if now-self.last_time > 15 or now < self.last_time - 2:
            raise ValueError("Flugzeugmodell wird nicht aktuell berechnet")
        items, weights = self.weights()
        if any(now-row["observed_at"] > MAX_OBSERVATION_AGE for row in items):
            raise ValueError("Flugzeugdaten sind veraltet")
        u, v = self.velocity(self.zeta, self.mean)
        coverage = 1 - np.exp(-weights.sum(axis=0))
        xs = PADDING_M + np.linspace(0, (EAST-WEST)*LONGITUDE_SCALE, 64)
        ys = PADDING_M + np.linspace(0, (NORTH-SOUTH)*METRES_PER_DEGREE, 64)

        def resample(field):
            along_x = np.array([np.interp(xs, self.x[0], row) for row in field])
            return np.array([np.interp(ys, self.y[:, 0], column) for column in along_x.T]).T

        east, north, support = (resample(field) for field in (u, v, coverage))
        x = np.array([PADDING_M + (row["lon"]-WEST)*LONGITUDE_SCALE for row in items])/self.dx
        y = np.array([PADDING_M + (row["lat"]-SOUTH)*METRES_PER_DEGREE for row in items])/self.dy
        i, j = np.floor(x).astype(int), np.floor(y).astype(int)
        fx, fy = x-i, y-j

        def sample(field):
            return ((1-fy)*((1-fx)*field[j, i] + fx*field[j, i+1])
                    + fy*((1-fx)*field[j+1, i] + fx*field[j+1, i+1]))

        residual_east = sample(u) - np.array([row["east"] for row in items])
        residual_north = sample(v) - np.array([row["north"] for row in items])
        rmse = float(np.sqrt(np.mean(residual_east**2 + residual_north**2)))
        altitudes = [row["alt_ft"] for row in items]
        return {
            "nx": 64, "ny": 64, "bounds": [WEST, SOUTH, EAST, NORTH],
            "vectors": np.round(np.stack((east, north), axis=-1).reshape(-1, 2), 3).tolist(),
            "support": np.round(support.ravel(), 3).tolist(), "level": "250hPa",
            "updated_at": self.last_time, "aircraft_count": len(items),
            "oldest_observation_s": round(max(now-row["observed_at"] for row in items), 1),
            "min_alt_ft": min(altitudes), "max_alt_ft": max(altitudes),
            "rmse_ms": round(rmse, 2), "warning": self.time_warning,
        }
