# Astrology engine R&D: Swiss Ephemeris via PHP FFI

> **Status: R&D only. Do not deploy to production.**
> Production use is on hold until (1) the Swiss Ephemeris licence is confirmed,
> (2) the new dependencies are approved and (3) these results are reviewed.
> Branch: `rnd/swisseph-ffi`.

## Goal

Port the vedicpanchanga.com Python calculation engine (kundali, panchang,
muhurta, festivals, transits, PDF) to native Laravel with no Python runtime.
Every calculation depends on Swiss Ephemeris, so step 0/1 proved that PHP can
call the C library through FFI with results identical to `pyswisseph`.

## What is in this step

| File | Purpose |
|---|---|
| `resources/swisseph/swe.h` | C declarations for the Swiss Ephemeris functions PHP calls |
| `resources/swisseph/preload.php` | `opcache.preload` script that lets PHP-FPM use FFI (see below) |
| `config/astrology.php` | Library path, ephemeris path, default timezone (`Asia/Kolkata`), default ayanamsa |
| `app/Services/Astrology/SwissEphemeris.php` | FFI binding: julian day, sidereal mode, ayanamsa, positions, houses, rise/set |
| `app/Services/Astrology/SwissEphemerisException.php` | Error type for load and calculation failures |
| `app/Console/Commands/AstroDoctor.php` | `php artisan astro:doctor` environment check |
| `tests/Feature/Services/Astrology/SwissEphemerisTest.php` | Parity tests against pyswisseph |
| `tests/Feature/Console/Commands/AstroDoctorTest.php` | Doctor success and failure modes |
| `tests/Fixtures/astrology/swisseph_reference.json` | Reference values generated from the Python backend |
| `storage/app/ephe/*.se1` | Ephemeris data (committed via a `storage/app/.gitignore` exception) |
| `storage/app/lib/libswe.so` | Native library (**not committed**, built per server) |

No existing route, model, migration, controller or provider was changed.

## Building libswe.so

Source: `https://github.com/aloistr/swisseph`, tag `v2.10.3final`
(commit `af9823fe7b06ffefe3d3968fdc5680be8b5eec5f`), AGPL edition.

```bash
git clone --depth 1 --branch v2.10.3final https://github.com/aloistr/swisseph /tmp/swisseph
make -C /tmp/swisseph libswe.so CFLAGS="-O2 -Wall -fPIC"
strip --strip-unneeded /tmp/swisseph/libswe.so
mkdir -p storage/app/lib
cp /tmp/swisseph/libswe.so storage/app/lib/libswe.so
```

- Requires `gcc` and `make`. Upstream's default `CFLAGS` are `-g` (no
  optimisation); always pass `-O2` as above.
- The library must be built on, or for, the target OS and CPU. The dev build is
  `ELF 64-bit x86-64` on Ubuntu 24.04 (glibc). An ARM server or Alpine (musl)
  image needs its own build.
- Dev build sha256: `101253b63731c3784a894fdbd74a89b4212790e44742de02022f2b295a94861c`.
- `resources/swisseph/swe.h` declares `int32` as `int`, which is correct for
  x86_64 and aarch64 Linux (`sweodef.h`). Re-check if the target changes.

## Ephemeris data

`storage/app/ephe/` holds `sepl_18.se1` (planets), `semo_18.se1` (Moon) and
`seas_18.se1` (asteroids), copied from the Python backend. These files cover
**1800 to 2399 CE**. Dates outside that range need additional files from the
upstream `ephe/` directory.

If the files are missing, Swiss Ephemeris silently falls back to its built-in
Moshier model, which is less accurate. `SwissEphemeris::position()` detects
this and throws, so it cannot pass unnoticed.

## Configuration

| Env key | Default |
|---|---|
| `ASTRO_SWE_LIBRARY_PATH` | `storage/app/lib/libswe.so` |
| `ASTRO_SWE_EPHEMERIS_PATH` | `storage/app/ephe` |
| `ASTRO_DEFAULT_TIMEZONE` | `Asia/Kolkata` |
| `ASTRO_DEFAULT_AYANAMSA` | `lahiri` |

This environment caches config (`bootstrap/cache/config.php`). After adding
or changing config run `php artisan config:clear` (or `config:cache`). Once
astro routes exist, also run `php artisan route:clear` (routes are cached too).

## Permissions

The PHP-FPM user (normally `www-data`) needs:

- read on `storage/app/lib/libswe.so` (`0644` is enough),
- read on `storage/app/ephe/*.se1` and execute (traverse) on the directories,
- read on `resources/swisseph/swe.h`.

`storage/` must not be on a `noexec` mount, or `dlopen` of the library fails.

## PHP runtime requirements

- PHP extension `ffi` (built into the Ubuntu PHP 8.5 packages here).
- Ubuntu's default is `ffi.enable = preload`. That allows FFI from the **CLI
  only** (artisan, PHPUnit), plus code that was preloaded by opcache.

Measured on this machine with the built-in web server (same restriction as
PHP-FPM):

| Setup | Result |
|---|---|
| Default `ffi.enable=preload`, no preload | **Fails**: `FFI API is restricted by "ffi.enable" configuration directive` |
| `opcache.preload=resources/swisseph/preload.php` | **Works**, FFI stays restricted for every other script |
| `ffi.enable=true` | Works, but opens FFI to all code on the server (not recommended) |

### Recommended PHP-FPM setup (preload)

Example `/etc/php/8.5/fpm/conf.d/99-vaastu-swisseph.ini`:

```ini
opcache.enable=1
opcache.preload=/path/to/vaastu-wisdom-laravel/resources/swisseph/preload.php
opcache.preload_user=www-data
```

Then `sudo systemctl restart php8.5-fpm`.

Caveats:

- `opcache.preload` is server-wide per FPM master, not per pool. The PHP 8.5
  FPM on this machine may serve other sites; check before enabling it there,
  or run this app on its own FPM master.
- Preloaded classes are fixed until FPM restarts. **Any deploy that changes
  `SwissEphemeris.php` or `SwissEphemerisException.php` needs an FPM restart.**
- `php artisan serve` / `composer run dev` start a web SAPI without preload,
  so astro HTTP endpoints will fail there until the dev server is started with
  the preload ini or `-d ffi.enable=1`. Artisan commands and tests are fine.

## Verifying an environment

```bash
php artisan astro:doctor
php artisan test --compact tests/Feature/Services/Astrology tests/Feature/Console
```

The tests skip themselves when the FFI extension or `libswe.so` is missing, so
CI and fresh clones without the native library do not fail.

## Results (2026-10-27, Ubuntu 24.04 x86_64, PHP 8.5.11 CLI)

### Accuracy

Reference values were generated from pyswisseph 2.10.03 (the library the
Python backend uses), reproducing the backend's real calls:

- flags `SIDEREAL | SWIEPH | SPEED`, mean node for Rahu,
- Placidus houses with the sidereal flag,
- sunrise, sunset, moonrise and moonset with default flags,
- 6 ayanamsas (Lahiri, KP new, KP old, Raman, True Chitra, Lahiri ICRC),
- 4 moments (1905, 1990, 2026, 2075) and 3 locations (New Delhi, Kelowna, Sydney).

| Check | Cases | Result |
|---|---|---|
| Julian day and ayanamsa | 72 | identical |
| 8 bodies x 6 values (lon, lat, dist, 3 speeds) | 576 bodies | identical |
| 12 cusps + ascendant + midheaven | 72 | identical |
| Sun and Moon rise/set | 48 | identical |

The tests use a tolerance of `1e-9` degrees. The observed difference was
exactly `0` for every value: the FFI binding is bit-identical to pyswisseph.
Suite: 8 tests, 994 assertions, all passing.

### Performance (per call, mean)

| Operation | PHP FFI | pyswisseph |
|---|---|---|
| Load library + header (once per request) | 0.8 ms | n/a |
| Planet position | ~16 us | ~13 us |
| Placidus houses | ~32 us | ~29 us |
| Rise/set | ~97 us | ~95 us |

FFI overhead is about 5-15% per call and negligible against a full chart.

### Unrelated existing issues found

`php artisan test` (full suite) fails 32 existing tests on this machine for
environment reasons, not because of this work:

- PHP 8.5 CLI has no `pdo_sqlite` extension (`could not find driver`), while
  `phpunit.xml` uses SQLite `:memory:`. Fix: `sudo apt install php8.5-sqlite3`.
- `ExampleTest` fails with `No application encryption key has been specified`
  (no `APP_KEY` in the testing environment).

## Phase 1: Kundali (2026-10-27)

### Code

| File | Ported from |
|---|---|
| `app/Services/Astrology/Kundali/KundaliCalculator.php` | `calculator.compute_chart` |
| `app/Services/Astrology/Kundali/Vargas.php` | `vargas.py` (D1-D60) |
| `app/Services/Astrology/Kundali/VimshottariDasha.php` | `calculator` dasha + `dasha_extras.py` |
| `app/Services/Astrology/Kundali/Ashtakavarga.php` | `calculator.compute_ashtakavarga` |
| `app/Services/Astrology/Kundali/Placements.php` | `placements.py` |
| `app/Services/Astrology/Kundali/Jaimini.php` | `jaimini.py` |
| `app/Services/Astrology/Kundali/Relationships.php` | `relationships.py` |
| `app/Services/Astrology/Kundali/Kalsarpa.php` | `kalsarpa.py` |
| `app/Services/Astrology/Kundali/Drishti.php` | `drishti.py` |
| `app/Services/Astrology/Ayanamsa.php` | `ayanamsa.py` |
| `app/Services/Astrology/Zodiac.php` | shared sign / nakshatra tables |
| `app/Services/Astrology/LocalTime.php` | pytz `localize(is_dst=False)` behaviour |
| `app/Services/Astrology/PythonMath.php` | Python `round`, `%`, `//` semantics |

### Endpoints (all behind `auth:sanctum` + `abilities:*`)

| Method | Path | Notes |
|---|---|---|
| GET | `/api/v1/astro/ayanamsas` | 7 options, Lahiri first |
| POST | `/api/v1/astro/kundali` | `birth_date` (Y-m-d, 1800-01-01 to 2399-12-31), `birth_time` (H:i), `latitude`, `longitude`, optional `timezone` (IANA, default `Asia/Kolkata`) and `ayanamsa` (default `lahiri`) |
| GET | `/api/v1/kundlis/{kundli}/chart` | Chart for a saved Kundli; optional `?timezone=&ayanamsa=`; 422 if birth date, time or coordinates are missing; 404 for another customer's Kundli |

Responses use the existing `ApiResponse` envelope with the chart in
`data.chart`, in exactly the shape of the Python `/api/calculate` response.
They are encoded with `JSON_PRESERVE_ZERO_FRACTION` so `1.0` stays `1.0`
(PHP would otherwise emit `1`, which typed clients such as Dart decode as an
int instead of a double).

### Porting rules that mattered

- **Python float semantics.** PHP `round()` disagreed with Python on 6 of 8
  edge cases (e.g. `2.675` to 2 places), and Python `1.0 // 0.1` is `9.0`.
  All rounding, `%` and `//` go through `PythonMath`.
- **Rounded longitudes.** Python rounds planet longitudes to 6 decimals before
  vargas, dashas and placements use them; the port does the same.
- **Dasha times** are kept as integer microseconds and reproduce CPython's
  `timedelta(days=float)` rounding.
- **Ambiguous / non-existent local times** follow pytz `is_dst=False`
  (standard-time offset). PHP alone would pick the DST offset for an
  ambiguous time.

### Results

| Check | Result |
|---|---|
| 14 reference charts (6 ayanamsas + tropical, both hemispheres, 1805-2350, DST gap and ambiguity, 1945 war time) | **identical** to Python after a JSON round trip: same keys, key order, types and values |
| 18 Pratyantar sets | identical |
| Full chart via `POST /api/v1/astro/kundali` | identical to the Python chart |
| Chart calculation time | ~1.8 ms per chart (PHP 8.5 CLI) |
| PHP compatibility | passes on PHP 8.5 and 8.3 (the project minimum) |

Test files: `tests/Feature/Services/Astrology/Kundali/KundaliCalculatorTest.php`,
`tests/Feature/Api/V1/AstrologyTest.php`, `tests/Feature/Api/V1/KundliChartTest.php`,
`tests/Unit/Services/Astrology/PythonMathTest.php`; fixture
`tests/Fixtures/astrology/kundali_reference.json`.

`KundliChartTest` (5 tests) needs a database and **could not run on this
machine** (no `pdo_sqlite`); it fails only with `could not find driver`.

### Intentional differences from Python

| Case | Python | Laravel | Reason |
|---|---|---|---|
| Kolkata births before 1906 | Howrah LMT `+05:53` | Madras Mean Time `+05:21:10` (1870-1906) | pytz disagrees with tzdata 2026a; ~32 min error in Python |
| Pre-standard-time births anywhere | offset rounded to whole minutes | exact offset, `+HH:MM:SS` in `local_time` | pytz minute rounding |
| No timezone given | guessed from lat/lon (`timezonefinder`) | `Asia/Kolkata` | Decision for this app |
| Unknown ayanamsa | silently uses Lahiri | 422 | Validation |
| Birth date outside 1800-2399 | calculated with lower-accuracy fallback or error | 422 | Ephemeris file range |

### Issues found in the Python project (not fixed there)

1. **Pre-1906 Indian charts are ~32 minutes off** (pytz offset, see above).
2. **Births above the Arctic Circle return HTTP 500.** Placidus houses are
   undefined there and `swe.houses_ex` raises. The Laravel port behaves the
   same (generic 500) for now; a fallback (e.g. Porphyry or whole-sign for the
   ascendant) needs a decision.
3. **Static `FFI::new()` is deprecated in PHP 8.5.** Not a Python issue, but
   found while porting: Step 1's wrapper used it and PHPUnit hid the warning.
   Fixed.

## Phase 2: Panchang (2026-10-27)

### Code (`app/Services/Astrology/Panchang/`)

| File | Ported from |
|---|---|
| `PanchangCalculator.php` | `advanced_panchang.compute_detailed_panchang` |
| `PanchangTables.php` | `constants.py` + `panchang_constants.py` |
| `Tyajyam.php` | `tyajyam.py` (all ten Tyajyam types) |
| `TamilCalendar.php` | `tamil_calendar.py` |
| `GowriPanchang.php`, `Hora.php`, `TimeSegments.php` | `gowri_panchang.py`, `hora.py` |
| `NallaNeram.php` | `nalla_neram.py` |
| `ExtraYogas.php` | `panchang_extras.py` (Ganda Mula, Ravi Yoga) |
| `JulianTime.php` | `_jd_to_local` / `_iso` (JD to local ISO, ties-to-even seconds) |
| `IsoInstant.php` | Python fixed-offset `datetime` / `timedelta` microsecond arithmetic |

`SwissEphemeris` gained `calendarDate()` (`swe_revjul`), `nextSolarEclipse()`
(`swe_sol_eclipse_when_glob`) and `nextLunarEclipse()` (`swe_lun_eclipse_when`);
`resources/swisseph/swe.h` declares them. They work under the PHP-FPM preload
setup (re-verified).

### Endpoint

| Method | Path | Notes |
|---|---|---|
| GET | `/api/v1/astro/panchang` | `latitude`, `longitude` (rounded to 4 decimals, as Python does), optional `date` (Y-m-d, 1800-03-01 to 2399-12-31, default today **in the requested timezone**) and `timezone` (default `Asia/Kolkata`). Response `data.panchang` has the exact shape of Python `/api/get-panchang`. |

The earliest date is 1800-03-01 because the panchang looks back up to 40 days
(solar month start); for early January 1800 that is outside the ephemeris file.

### Results

| Check | Result |
|---|---|
| 17 reference days: DrikPanchang-pinned Delhi 17-19 Sep 2026, lunar eclipse (3 Mar 2026), solar eclipse (12 Aug 2026), Guru and Sukra Asthamanam, Wednesday (Abhijit suppressed), Tuesday (night Dur Muhurtam), Makara Sankranti, Tamil New Year, Margazhi, Kelowna, Sydney and New York DST changes, 1950, 2099 | **identical** to Python after a JSON round trip, including microsecond Gowri/Hora segment times |
| Full panchang via `GET /api/v1/astro/panchang` | identical to the Python panchang |
| Time per panchang | ~35 ms in PHP vs ~170 ms in Python (Python caches results because of this) |
| PHP compatibility | passes on PHP 8.5 and 8.3 |

Tests: `tests/Feature/Services/Astrology/Panchang/PanchangCalculatorTest.php`
plus panchang cases in `tests/Feature/Api/V1/AstrologyTest.php`; fixture
`tests/Fixtures/astrology/panchang_reference.json`.

### Intentional differences from Python

| Case | Python | Laravel |
|---|---|---|
| No `date` given | server's local date (`date.today()`) | today in the requested timezone |
| No `timezone` given | guessed from lat/lon | `Asia/Kolkata` |
| Result caching | in-process LRU (128 entries) | none (35 ms); can add Laravel cache later if needed |

### Issues found in the Python project (not fixed there)

4. **`advanced_panchang.py` does not set the ephemeris path itself.** It relies
   on `calculator.py` (or `transits.py`) having been imported first. The API
   and the test suite do import them, but any script that imports
   `advanced_panchang` alone silently runs on the low-accuracy Moshier model
   (tithi/nakshatra ends 1-3 seconds off). This bit the first fixture run.
5. **`tamil_calendar._jd_to_local_date` drops the day carry** when rounding
   reaches 24:00 (`hour % 24` with no `+1 day`). Only affects a sankranti in
   the last half-second before UTC midnight; the port keeps the same behaviour
   for parity.

## Phase 3: Transits, Muhurta, Festivals (2026-10-27)

### Code

| File | Ported from |
|---|---|
| `app/Services/Astrology/Transits/TransitCalculator.php` | `transits.compute_transits` |
| `app/Services/Astrology/Muhurta/MuhurtaFinder.php` | `muhurta.find_muhurtas` (scoring, vetoes, Bhadra trimming) |
| `app/Services/Astrology/Muhurta/MuhurtaPurposes.php` | `muhurta.PURPOSES` (13 purposes) |
| `app/Services/Astrology/Festivals/FestivalCalculator.php` | `festivals.compute_festivals` (all day pickers, events, periods) |
| `app/Services/Astrology/Festivals/FestivalRules.php` | festival rule tables and English names |
| `app/Services/Astrology/Festivals/FestivalSky.php`, `SkyDay.php`, `SkySegment.php`, `LunarMonth.php` | `festivals._Sky`, `_Day`, `_Segment`, `_Month` |
| `app/Services/Astrology/Panchang/LunarAngles.php` | shared Sun/Moon angle bisection (extracted from `PanchangCalculator`) |

`SwissEphemeris::nextSolarEclipse()` / `nextLunarEclipse()` now return the
eclipse type flags with the times (`ECLIPSE_*` constants), needed for the
total / annular / partial / penumbral labels.

### Endpoints

| Method | Path | Notes |
|---|---|---|
| GET | `/api/v1/astro/transits` | `start_date` (default today in the timezone), `end_date` (default +365 days, at most 1096 days), `timezone`, flags `include_signs`, `include_nakshatras`, `include_retrograde` (default true), `include_moon`, `moon_nakshatras` (default false; `true/false/1/0`) |
| GET | `/api/v1/astro/muhurta-purposes` | the 13 purposes |
| POST | `/api/v1/astro/muhurta` | `purpose`, `start_date`, `end_date` (at most 120 days), `latitude`, `longitude`, optional `timezone`, `birth_rashi_id` (1-12), `birth_nakshatra_id` (1-27), `min_score` (default 60), `limit` (default 30) |
| GET | `/api/v1/astro/festivals` | `latitude`, `longitude`, optional `year` (1900-2100, default current year in the timezone), `timezone` |

Each response has exactly the shape of the matching Python endpoint, inside
`data.transits`, `data.purposes`, `data.muhurta` or `data.festivals`.

### Results

| Check | Result |
|---|---|
| 4 transit ranges (1999, 2026, Moon with nakshatras, flags off, Kelowna) | **identical** |
| 7 muhurta searches: every veto (combustion, Chaturmas, Kharmas, Adhika Jyeshtha 2026), Bhadra trimming, native rashi / nakshatra, Sydney, Kelowna | **identical** |
| 13 muhurta purposes | identical |
| Festival years Delhi 2026, Delhi 2027 (Python pins both against DrikPanchang), Chennai 2025, Sydney 2026, Delhi 2100 | **identical** |
| Kelowna 2026 | same festival dates, ids and periods; times after 1 Nov differ (see below) |
| Delhi 1900 | differs: pre-1906 Kolkata offset (same pytz issue as Phase 1) |
| Endpoints | transits, muhurta and festivals over HTTP identical to Python |
| Speed | transits ~150 ms per year; muhurta ~30 ms per day scanned (120 days ~3.6 s, similar to Python); festivals ~0.9 s per year (Python ~0.7 s) |
| PHP compatibility | 86 astrology tests pass on PHP 8.5, 83 on PHP 8.3 |

### Intentional differences from Python

| Case | Python | Laravel |
|---|---|---|
| America/Vancouver from 2026-11-01 | pytz 2026a: back to PST (-08:00) | system tzdata 2026e: British Columbia's permanent UTC-7 |
| Transit time rounding to 24:00:00 | `datetime(..., hour=24)` raises, request fails | carries into the next day |
| Transit range | unlimited | at most 1096 days (load protection) |
| Muhurta range / unknown purpose | HTTP 400 | HTTP 422 validation errors |

### Issues found in the Python project (not fixed there)

6. **pytz is behind the tz database.** The bundled 2026a data misses British
   Columbia's switch to permanent UTC-7 on 2026-11-01, so Vancouver-area times
   on vedicpanchanga.com will be an hour off from November. pytz ships its own
   copy of the data; updating the package (or moving to `zoneinfo` with the
   system tzdata) fixes it.
7. **`transits._jd_to_iso` can crash** when an event time rounds up to
   24:00:00 (`datetime` rejects hour 24, so the whole request returns 500).
8. **`festivals.py` also relies on another module setting the ephemeris path**
   (same as issue 4).

## Licensing

Swiss Ephemeris is dual-licensed: **AGPL** or the paid **Swiss Ephemeris
Professional Licence** from Astrodienst. The AGPL requires the source of the
whole networked application to be offered to its users. Vaastu Wisdom is closed
source and commercial, so the AGPL edition must **not** be assumed suitable for
production. This R&D build uses the AGPL edition only for evaluation.
Decision needed before production: buy the Professional Licence, or get legal
sign-off.

## Phase 4: Kundali PDF report (2026-10-27)

`mpdf/mpdf` ^8.3 was approved and installed (adds `setasign/fpdi`,
`paragonie/random_compat` and two small `mpdf/*` packages; no existing
package versions changed).

### Code

| File | Ported from |
|---|---|
| `app/Services/Astrology/Pdf/KundaliReport.php` | `pdf/report.render_pdf` (page order, section index) |
| `app/Services/Astrology/Pdf/ReportCanvas.php` | `pdf/core/text.py` + `layout.py` (mPDF wrapper in points, per-script runs, footer) |
| `app/Services/Astrology/Pdf/ReportLabels.php` | `pdf/core/i18n/__init__.py` |
| `app/Services/Astrology/Pdf/ReportFormat.php` | `pdf/core/formatters.py`, `dasha.py` |
| `app/Services/Astrology/Pdf/ChartDrawer.php` | `pdf/core/chart.py` (North / South Indian) |
| `app/Services/Astrology/Pdf/Pages/*` | `pdf/core/sections.py` and `pdf/pages/*.py`, one class per module |
| `app/Services/Astrology/SadeSati.php` | `sade_sati.py` |
| `app/Services/Astrology/MangalDosha.php` | `mangal.py` |
| `app/Console/Commands/AstroPdfFonts.php` | new: `astro:pdf-fonts` builds the mPDF font cache |
| `resources/astrology-pdf/locales/*.php` | the 15 `pdf/core/i18n/locales/*.py` dictionaries, generated mechanically |
| `resources/astrology-pdf/fonts/` | patched Noto fonts, `OFL.txt` and `prepare_noto_for_mpdf.py` |
| `resources/astrology-pdf/om.svg` | `pdf/assets/om.svg` |

`SwissEphemeris::siderealTime()` (`swe_sidtime`) was added for the SID field.
The page code keeps Python's point coordinates; the canvas converts to mm.

### Endpoint

| Method | Path | Notes |
|---|---|---|
| POST | `/api/v1/astro/kundali/pdf` | `birth_date` (1800-03-01 to 2399-12-31, the panchang look-back limit), `birth_time`, `latitude`, `longitude`, optional `timezone` (default `Asia/Kolkata`), `ayanamsa`, `name`, `sex` (`Male`/`Female`), `place_name`, `lang` (15 languages, default `en`), `chart_style` (`north`/`south`; Tamil always south). Returns `application/pdf` inline with a UTF-8 file name and an ASCII fallback. |

### Fonts: what mPDF could not load, and the fix

mPDF 8.3 rejected every current Noto font the Python report uses:

| Problem | Affected | Fix |
|---|---|---|
| GSUB/GPOS contextual lookups format 3 ("GPOS Lookup Type 5, Format 3 not supported") | Noto Sans, Devanagari, Bengali, Arabic | rewritten as the equivalent chaining-context lookups (lossless) |
| `UseMarkFilteringSet` lookups ("contains MarkGlyphSets") | Devanagari, Bengali, Tamil, Arabic | flag dropped (small approximation; output checked visually against HarfBuzz) |
| Persian letters decomposed into dotless base + dot marks | Noto Sans Arabic | mPDF's Arabic joiner breaks them; Arabic and Persian use mPDF's bundled **XB Riyaz** |
| CFF outlines (`.otf`) | Noto Sans SC / JP | not loadable; Chinese and Japanese use mPDF's bundled **Sun-ExtA** (covers every CJK character in the labels, kana included) |

`prepare_noto_for_mpdf.py` reproduces the shipped TTFs byte for byte from the
vedicpanchanga.com originals. **Deploy step:** run `php artisan astro:pdf-fonts`
once per server; the first parse of all fonts takes about 1.5 minutes, then
reports render in 0.4-2 s. mPDF's cache is kept in
`storage/framework/cache/mpdf` with automatic cleanup disabled (by default it
deletes the parsed fonts after an hour).

### Results

| Check | Result |
|---|---|
| Page-1 detail values, 4 births (Lahiri, Raman, KP New, tropical; Vancouver DST ambiguity; Sydney) x 5 languages | **identical** to Python |
| Sade Sati periods (120 years) and Mangal Dosha, same births | **identical** |
| English report, same birth as Python | same 19 pages, **identical extracted text**, pixel-identical on 18/19 pages at 50 dpi (page 18: justified paragraph wraps slightly differently) |
| Russian, Japanese, Chinese reports | identical extracted text |
| Hindi, Tamil, Bengali, Arabic, Persian, Hebrew | checked visually against the Python report; complex-script text extracts differently, as expected |
| All 15 languages | 19 pages each, no errors |
| Speed (warm cache) | 0.4-0.7 s for Latin, CJK, Tamil, Arabic, Hebrew; ~1 s Bengali; ~2 s Devanagari (Python: 0.8-2 s) |
| Tests | 103 astrology tests pass on PHP 8.5 and 8.3 |

Test files: `tests/Feature/Services/Astrology/Pdf/KundaliReportTest.php`, the
new cases in `tests/Feature/Api/V1/AstrologyTest.php`; fixture
`tests/Fixtures/astrology/phase4_reference.json`.

### Intentional differences from Python (bugs fixed in the port)

| Case | Python | Laravel |
|---|---|---|
| Multi-word Arabic, Persian and Hebrew labels | each word is a separate run drawn left to right, so **word order is reversed** (e.g. "الكواكب مواقع") | one shaped run per script, runs ordered by the first strong letter (Unicode bidi paragraph direction) |
| Persian words with a zero-width non-joiner (e.g. ماه‌های) | ZWNJ falls to the Latin font and splits the word | ZWNJ stays inside the Persian run |
| Hyphens and digits in Bengali text | drawn in the Bengali font, which has no hyphen: **missing glyphs** | Latin runs use Noto Sans |
| File name for non-Latin names | `isalnum()` drops vowel signs (आरव शाह -> आरवशह) | combining marks kept; UTF-8 `filename*` plus ASCII fallback |
| Sade Sati horizon for births after ~2280 | runs past the ephemeris files (silent Moshier fallback) | stops at 2399-12-31 |
| Arabic/Persian and CJK typefaces | Noto Sans Arabic / SC / JP | XB Riyaz / Sun-ExtA (see Fonts) |
| Footer and header brand | `vedicpanchanga.com` hard-coded | `ASTRO_PDF_BRAND`, default `vedicpanchanga.com` |

### Issues found in the Python project (not fixed there)

9. **Reversed word order** in every multi-word Arabic, Persian and Hebrew PDF
   label (see above).
10. **Bengali PDFs lose every hyphen** in mixed text such as "নক্ষত্র - পাদ".
11. **Persian ZWNJ words are split** across fonts in the PDF.
12. Hebrew Regular and Bold in `pdf/fonts` are the same file, so Hebrew bold
    never renders bold (carried over unchanged).

### Licensing notes for the PDF stack

- `mpdf/mpdf` is **GPL-2.0-only**. Running it on your own server is not
  distribution, but distributing the application (e.g. to a client) would
  require the whole application under the GPL.
- **Sun-ExtA** (CJK) carries a Microsoft typography licence string ("use as
  permitted by the license terms for the product in which this font is
  included"); its terms for commercial embedding are unclear. Alternative:
  convert Noto Sans SC / JP (OFL) to TrueType outlines with fontTools (about
  20 MB of font files, slower first parse).
- **XB Riyaz** (Arabic/Persian) says "GNU General Public License" in the font
  but mPDF's info file shows OFL 1.1; confirm before production.
- The Noto fonts are OFL 1.1 (no Reserved Font Name); modified copies may be
  redistributed with `OFL.txt`.

## Next steps

1. Review the Phase 1-4 results.
2. Run `KundliChartTest` where `pdo_sqlite` is available
   (`sudo apt install php8.5-sqlite3`).
3. Decide the polar-latitude behaviour (affects kundali and panchang).
4. Decide the PDF brand (`ASTRO_PDF_BRAND`) and the CJK / Arabic font
   licensing before production.
