#!/usr/bin/env python3
"""Fast Python translation of ``hard_rectangles.f``.

The program solves the orientational distribution of a uniform fluid of
hard rectangles using the same scaled-particle free-energy model and Picard
iteration as the Fortran program.

Input (default: hard_rectangles.inp)
------------------------------------
One line containing::

    kappa  eta  mixing_parameter

Outputs
-------
``h_phi.dat``
    Gauss-Legendre abscissa and orientational distribution.
``hard_rectangles.dat``
    Appended thermodynamic and order-parameter results.

Acceleration
------------
The excluded-area matrix is precomputed once.  Every Picard iteration then
uses BLAS-backed NumPy matrix-vector products instead of nested Python loops.
This is the natural vectorized form of the integral equation.
"""

from __future__ import annotations

import argparse
from dataclasses import dataclass
from pathlib import Path
import time

import numpy as np


N_DEFAULT = 100
TOL_DEFAULT = 1.0e-8
MAX_ITER_DEFAULT = 50_000


@dataclass(frozen=True)
class Parameters:
    kappa: float
    eta: float
    mixing: float


def read_parameters(path: Path) -> Parameters:
    try:
        values = np.fromstring(path.read_text(), sep=" ")
    except OSError as exc:
        raise SystemExit(f"Cannot read parameter file '{path}': {exc}") from exc

    if values.size < 3:
        raise SystemExit(
            f"'{path}' must contain at least three numbers: kappa eta mixing"
        )

    p = Parameters(float(values[0]), float(values[1]), float(values[2]))
    if p.kappa <= 0.0:
        raise SystemExit("kappa must be positive")
    if not (0.0 < p.eta < 1.0):
        raise SystemExit("eta must satisfy 0 < eta < 1")
    if not (0.0 <= p.mixing < 1.0):
        raise SystemExit("mixing must satisfy 0 <= mixing < 1")
    return p


def gauss_legendre_grid(n: int, gauss_file: Path | None) -> tuple[np.ndarray, np.ndarray]:
    """Read the original grid when available, otherwise generate it."""
    if gauss_file is not None and gauss_file.exists():
        data = np.loadtxt(gauss_file, dtype=np.float64)
        if data.ndim != 2 or data.shape[1] < 2:
            raise SystemExit(f"Invalid Gauss-Legendre file: '{gauss_file}'")
        if data.shape[0] != n:
            raise SystemExit(
                f"'{gauss_file}' contains {data.shape[0]} nodes, but n={n}"
            )
        return np.ascontiguousarray(data[:, 0]), np.ascontiguousarray(data[:, 1])

    x, w = np.polynomial.legendre.leggauss(n)
    return np.ascontiguousarray(x), np.ascontiguousarray(w)


def excluded_area_matrix(x: np.ndarray, kappa: float) -> np.ndarray:
    """A_ij = area(pi*x_i - pi*x_j)."""
    dphi = np.pi * (x[:, None] - x[None, :])
    return (
        0.5 * (kappa + 1.0 / kappa) * np.abs(np.sin(dphi))
        + np.abs(np.cos(dphi))
    )


def solve_distribution(
    A: np.ndarray,
    w: np.ndarray,
    eta: float,
    mixing: float,
    tol: float,
    max_iter: int,
    verbose: bool = False,
) -> tuple[np.ndarray, int, float]:
    """Solve the Picard fixed-point equation by simultaneous mixing.

    This is the standard Picard/Jacobi update intended by the Fortran code,
    but evaluates all angular nodes together.  Its converged fixed point is
    the same integral equation as the original node-by-node implementation.
    """
    n = w.size
    h = np.full(n, 1.0 / (2.0 * np.pi), dtype=np.float64)
    coefficient = -2.0 * eta * np.pi / (1.0 - eta)
    one_minus_mixing = 1.0 - mixing

    for iteration in range(1, max_iter + 1):
        psi = coefficient * (A @ (w * h))

        # Shift the exponential to avoid overflow/underflow.  The shift
        # cancels exactly in the normalized distribution.
        psi_max = float(np.max(psi))
        exp_psi = np.exp(psi - psi_max)
        normalization = np.pi * np.dot(w, exp_psi)
        target = exp_psi / normalization

        new_h = mixing * h + one_minus_mixing * target
        error = float(np.sum(np.abs(new_h - target)))
        h = new_h

        if verbose and (iteration == 1 or iteration % 100 == 0 or error < tol):
            print(f"iteration {iteration:6d}: error = {error:.6e}")

        if error < tol:
            return h, iteration, error

    raise RuntimeError(
        f"Picard iteration did not converge after {max_iter} iterations; "
        f"last error = {error:.6e}. Try a larger mixing parameter."
    )


def order_parameter(h: np.ndarray, x: np.ndarray, w: np.ndarray, order: int) -> float:
    km = int(np.argmax(h))
    value = np.pi * np.dot(w * h, np.cos(np.pi * order * (x - x[km])))
    return abs(float(value))


def thermodynamics(
    h: np.ndarray,
    A: np.ndarray,
    w: np.ndarray,
    kappa: float,
    eta: float,
) -> tuple[float, float, float, float]:
    y = eta / (1.0 - eta)
    cc = (kappa + 1.0 / kappa + 2.0) / np.pi

    energy_isotropic = eta * (
        np.log(y) - 1.0 - np.log(2.0 * np.pi) + y * cc
    )
    pressure_isotropic = y + y * y * cc

    weighted_h = w * h
    ss = np.pi**2 * float(weighted_h @ (A @ weighted_h))

    coefficient = -2.0 * eta * np.pi / (1.0 - eta)
    psi = coefficient * (A @ weighted_h)
    psi_max = float(np.max(psi))
    normalization_log = (
        np.log(np.pi * np.dot(w, np.exp(psi - psi_max))) + psi_max
    )

    energy = eta * (np.log(y) - 1.0 - y * ss - normalization_log)
    pressure = y + y * y * ss
    return (
        float(energy_isotropic),
        float(pressure_isotropic),
        float(energy),
        float(pressure),
    )


def write_outputs(
    profile_path: Path,
    results_path: Path,
    x: np.ndarray,
    h: np.ndarray,
    row: tuple[float, ...],
) -> None:
    np.savetxt(profile_path, np.column_stack((x, h)), fmt="  %12.6e  %12.6e")
    with results_path.open("a", encoding="utf-8") as stream:
        stream.write("  " + "  ".join(f"{value:12.6e}" for value in row) + "\n")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", type=Path, default=Path("hard_rectangles.inp"))
    parser.add_argument("--gauss", type=Path, default=Path("gauss.dat"),
                        help="Gauss-Legendre file; generated internally if absent")
    parser.add_argument("--profile", type=Path, default=Path("h_phi.dat"))
    parser.add_argument("--output", type=Path, default=Path("hard_rectangles.dat"))
    parser.add_argument("--nodes", type=int, default=N_DEFAULT)
    parser.add_argument("--tol", type=float, default=TOL_DEFAULT)
    parser.add_argument("--max-iter", type=int, default=MAX_ITER_DEFAULT)
    parser.add_argument("--verbose", action="store_true")
    parser.add_argument("--timing", action="store_true")
    return parser


def main() -> None:
    args = build_parser().parse_args()
    if args.nodes < 2:
        raise SystemExit("--nodes must be at least 2")
    if args.tol <= 0.0:
        raise SystemExit("--tol must be positive")

    params = read_parameters(args.input)
    x, w = gauss_legendre_grid(args.nodes, args.gauss)

    start = time.perf_counter()
    A = excluded_area_matrix(x, params.kappa)
    h, iterations, error = solve_distribution(
        A, w, params.eta, params.mixing, args.tol, args.max_iter, args.verbose
    )

    eta_it = 1.0 / (
        1.0 + 2.0 * (params.kappa + 1.0 / params.kappa + 2.0) / (15.0 * np.pi)
    )
    eta_in = 1.0 / (
        1.0 + 2.0 * (params.kappa + 1.0 / params.kappa - 2.0) / (3.0 * np.pi)
    )
    q2 = order_parameter(h, x, w, 2)
    q4 = order_parameter(h, x, w, 4)
    energy_i, pressure_i, energy, pressure = thermodynamics(
        h, A, w, params.kappa, params.eta
    )

    row = (
        params.kappa,
        params.eta,
        eta_in,
        eta_it,
        q2,
        q4,
        energy_i,
        pressure_i,
        energy,
        pressure,
    )
    write_outputs(args.profile, args.output, x, h, row)

    elapsed = time.perf_counter() - start
    print(
        f"Converged in {iterations} iterations; error = {error:.3e}; "
        f"q2 = {q2:.6g}; q4 = {q4:.6g}"
    )
    if args.timing:
        print(f"Elapsed time: {elapsed:.6f} s")


if __name__ == "__main__":
    main()
