Ë
    }D™jÝf ã                   ó  — U d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZmZmZmZmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZmZmZmZmZmZm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* dZ+dZ,dZ-ee.d<   dZ/ee.d<   dZ0ee.d<   dZ1ee.d<   dZ2i dd“dd“dd“dd“dd “d!d"“d#d$“d%d&“d'd(“d)d*“d+d,“d-d.“d/d0“d1d2“d3d4“d5d6“d7d8“d9d:d;d<d=œ¥Z3ee e4f   e.d><   d?d@dAdBdCdDdEdFœZ5ee e4f   e.dG<   g dH¢Z6ee    e.dI<   dJdKiZ7ee8e8f   e.dL<   d+d-dMœZ9ee e f   e.dN<   g dO¢dP„ dQ„ dRœg dO¢dS„ dT„ dRœg dU¢dV„ dWœg dX¢dY„ dWœdZœZ:ee ee8ef   f   e.d[<   d\Z;d]e8fd^„Z<e	 dxd_e8d`dadbe=dce=ddee=   f
de„«       Z>e G df„ da«      «       Z?e G dg„ dh«      «       Z@ G di„ dj«      ZAeBdkk(  räddllCm Z  g dm¢ZDee    e.dn<   eAj‹                  doeD¬p«      ZF eGeFj�                  «        eGeFj’                  «        eGeFj”                  «        eGeFj–                  «        eGeFj˜                  «        eGdq«        eGeFjš                  «       eFj�                  drd¬s«      ZO eP e
j¢                  «       dtz  dudv¬w«      5 ZReRj§                  eO«       ddd«       yy# 1 sw Y   yxY w)ya  
Astrological Subject Factory Module

This module provides factory classes for creating astrological subjects with comprehensive
astrological calculations including planetary positions, house cusps, aspects, and various
astrological points.

The main factory class AstrologicalSubjectFactory offers multiple creation methods for
different initialization scenarios, supporting both online and offline calculation modes,
various zodiac systems (Tropical/Sidereal), house systems, and coordinate perspectives.

Key Features:
    - Planetary position calculations for all traditional and modern planets
    - House cusp calculations with multiple house systems
    - Lunar nodes, Lilith points, asteroids, and trans-Neptunian objects
    - Arabic parts (lots) calculations
    - Fixed star positions
    - Automatic location data fetching via GeoNames API
    - Comprehensive timezone and coordinate handling
    - Flexible point selection for performance optimization

Classes:
    ChartConfiguration: Configuration settings for astrological calculations
    LocationData: Geographical location information and utilities
    AstrologicalSubjectFactory: Main factory for creating astrological subjects

Author: Giacomo Battaglia
Copyright: (C) 2025 Kerykeion Project
License: AGPL-3.0
é    N)Údatetime)Úgetenv)ÚPath)ÚOptionalÚListÚDictÚAnyÚget_args)Ú	dataclassÚfield)Úcontextmanager)ÚFetchGeonames)	ÚKerykeionExceptionÚ
ZodiacTypeÚAstrologicalSubjectModelÚ	PointTypeÚSiderealModeÚHousesSystemIdentifierÚPerspectiveTypeÚAstrologicalPointÚHouses)Úget_kerykeion_point_from_degreeÚget_planet_houseÚcheck_and_adjust_polar_latitudeÚcalculate_moon_phaseÚdatetime_to_julianÚnormalize_zodiac_type)ÚDEFAULT_ACTIVE_POINTSzcentury.boyÚKERYKEION_GEONAMES_USERNAMEÚFAGAN_BRADLEYÚDEFAULT_SIDEREAL_MODEÚPÚ DEFAULT_HOUSES_SYSTEM_IDENTIFIERÚTropicalÚDEFAULT_ZODIAC_TYPEzApparent GeocentricÚDEFAULT_PERSPECTIVE_TYPEé   ÚSunÚMooné   ÚMercuryé   ÚVenusé   ÚMarsé   ÚJupiteré   ÚSaturné   ÚUranusé   ÚNeptuneé   ÚPlutoé	   ÚMean_North_Lunar_Nodeé
   ÚTrue_North_Lunar_Nodeé   ÚMean_Lilithé   ÚTrue_Lilithé   ÚEarthé   ÚChironé   ÚPholusé   é   é   é   é   )ÚCeresÚPallasÚJunoÚVestaÚSTANDARD_PLANETSi i	a i¬ i i2q  ira iPÃ  )ÚErisÚSednaÚHaumeaÚMakemakeÚIxionÚOrcusÚQuaoarÚTNO_PLANETS)ÚRegulusÚSpicaÚ	AldebaranÚAntaresÚSiriusÚ	FomalhautÚAlgolÚ
BetelgeuseÚCanopusÚProcyonÚArcturusÚPolluxÚDenebÚAltairÚRigelÚAchernarÚCapellaÚVegaÚAlcyoneÚAlpheccaÚAlgorabÚDeneb_AlgediÚAlkaidÚFIXED_STARSro   zDeneb AlgediÚFIXED_STAR_SWE_NAMES)ÚMean_South_Lunar_NodeÚTrue_South_Lunar_NodeÚOPPOSITE_POINTS)Ú	Ascendantr(   r)   c                 ó   — | |z   |z
  S ©N© ©ÚascÚsunÚmoons      úr/var/www/html/Astrologybackend/backend/venv/lib/python3.12/site-packages/kerykeion/astrological_subject_factory.pyú<lambda>r   ©   s   € ¨c°D©j¸3Ñ.>€ ó    c                 ó   — | |z   |z
  S rx   ry   rz   s      r~   r   r   ª   s   € °°c±	¸DÑ0@€ r€   )ÚrequiredÚday_formulaÚnight_formulac                 ó   — | |z   |z
  S rx   ry   rz   s      r~   r   r   ®   s   € ¨c°C©i¸$Ñ.>€ r€   c                 ó   — | |z   |z
  S rx   ry   rz   s      r~   r   r   ¯   s   € °°d±
¸SÑ0@€ r€   )rv   r-   r(   c                 ó   — | |z   |z
  S rx   ry   )r{   Úvenusr|   s      r~   r   r   ³   s   € ¨3°©;¸Ñ+<€ r€   )r‚   Úformula)rv   r1   r3   c                 ó   — | |z   |z
  S rx   ry   )r{   ÚjupiterÚsaturns      r~   r   r   ·   s   € °°g±ÀÑ0F€ r€   )ÚPars_FortunaeÚPars_SpiritusÚPars_AmorisÚ
Pars_FideiÚARABIC_PARTS_CONFIGa½  
********
NO GEONAMES USERNAME SET!
Using the default geonames username is not recommended, please set a custom one!
You can get one for free here:
https://www.geonames.org/login
You can set the username via the KERYKEION_GEONAMES_USERNAME environment variable
or by passing the geonames_username parameter.
Keep in mind that the default username is limited to 2000 requests per hour and is shared with everyone else using this library.
********Úreturnc                  ó0   — t        t        «      xs t        S )zêGet geonames username from environment variable or return default.

    Priority:
    1. Environment variable KERYKEION_GEONAMES_USERNAME
    2. Default value (century.boy)

    Returns:
        str: The geonames username to use.
    )r   ÚGEONAMES_USERNAME_ENV_VARÚDEFAULT_GEONAMES_USERNAMEry   r€   r~   Ú_get_geonames_usernamer–   É   s   € ô Ô+Ó,ÒIÔ0IÐIr€   Ú	ephe_pathÚconfigÚChartConfigurationÚlngÚlatÚaltc              #   ó„  K  — t        j                  | «       t         j                  t         j                  z  }d}|j                  dk(  r|t         j
                  z  }nb|j                  dk(  r|t         j                  z  }n?|j                  dk(  r0|t         j                  z  }t        j                  |||xs d«       d}|j                  dk(  rŒ|t         j                  z  }|j                  dk(  r:t        j                  t         j                  |j                  |j                  «       n0t        j                  t!        t         d	|j                  › �«      «       	 |–— |rt        j                  ddd«       t        j"                  «        y
# |rt        j                  ddd«       t        j"                  «        w xY w­w)a¼  Context manager that isolates Swiss Ephemeris configuration.

    Responsibilities:
        - Set ephemeris path and calculation flags
        - Configure perspective (true geo / helio / topo)
        - Configure sidereal mode when needed (v5.12: 48 named modes + USER)
        - Apply topocentric observer only inside the with-block
        - Yield iflag for calculations
        - Reset topocentric coordinates afterward (defensive)

    Sidereal Mode Handling (v5.12):
        Named modes (e.g. ``LAHIRI``, ``FAGAN_BRADLEY``) are resolved via
        ``getattr(swe, f"SIDM_{mode}")`` -- each named mode encodes its own
        reference epoch and ayanamsa value internally.

        The ``USER`` mode requires two additional parameters on the config:
        ``custom_ayanamsa_t0`` (Julian Day of the reference epoch when the
        tropical and sidereal zodiacs are considered to coincide) and
        ``custom_ayanamsa_ayan_t0`` (the ayanamsa offset in degrees at that
        epoch). The Swiss Ephemeris extrapolates for other dates using its
        precession model.

    Args:
        ephe_path: Path containing Swiss Ephemeris data files.
        config: Validated chart configuration.
        lng: Observer longitude (used for topocentric charts).
        lat: Observer latitude (used for topocentric charts).
        alt: Observer altitude (meters) for topocentric charts.

    Yields:
        int: iflag to be passed to swe.calc_ut / swe.fixstar_ut.
    FzTrue GeocentricÚHeliocentricÚTopocentricç        TÚSiderealÚUSERÚSIDM_N)ÚsweÚset_ephe_pathÚ
FLG_SWIEPHÚ	FLG_SPEEDÚperspective_typeÚFLG_TRUEPOSÚ
FLG_HELCTRÚFLG_TOPOCTRÚset_topoÚzodiac_typeÚFLG_SIDEREALÚsidereal_modeÚset_sid_modeÚ	SIDM_USERÚcustom_ayanamsa_t0Úcustom_ayanamsa_ayan_t0ÚgetattrÚclose)r—   r˜   rš   r›   rœ   ÚiflagÚ	topo_useds          r~   Úephemeris_contextr¸   Ö   sX  è ø€ ôP ×Ñ�iÔ Ü�N‰NœSŸ]™]Ñ*€Eà€Ið ×ÑÐ"3Ò3Ø”—‘Ñ ‰Ø	×	 Ñ	  NÒ	2Ø”—‘Ñ‰Ø	×	 Ñ	  MÒ	1Ø”—‘Ñ ˆÜ�‰�S˜#˜sšz cÔ*Øˆ	ð ×Ñ˜ZÒ'Ø”×!Ñ!Ñ!ˆØ×Ñ 6Ò)ä×ÑœSŸ]™]¨F×,EÑ,EÀv×GeÑGeÕfä×ÑœW¤S¨E°&×2FÑ2FÐ1GÐ*HÓIÔJðØŠñ Ü�L‰L˜˜c 3Ô'ä�	‰	�øñ Ü�L‰L˜˜c 3Ô'ä�	‰	�üs   ‚EG ÅF Å .G Æ/F=Æ=G c                   óˆ   — e Zd ZU dZeZeed<   dZe	e
   ed<   eZeed<   eZeed<   dZe	e   ed<   dZe	e   ed<   dd	„Zdd
„Zy)r™   ao  
    Configuration settings for astrological chart calculations.

    This class encapsulates all the configuration parameters needed for astrological
    calculations, including zodiac type, coordinate systems, house systems, and
    calculation perspectives. It provides validation to ensure compatible settings
    combinations.

    Attributes:
        zodiac_type (ZodiacType): The zodiac system to use ('Tropical' or 'Sidereal').
            Defaults to 'Tropical'.
        sidereal_mode (Optional[SiderealMode]): The sidereal calculation mode when using
            sidereal zodiac. Only required/used when zodiac_type is 'Sidereal'.
            Defaults to None (auto-set to FAGAN_BRADLEY for sidereal).
        houses_system_identifier (HousesSystemIdentifier): The house system to use for
            house cusp calculations. Defaults to 'P' (Placidus).
        perspective_type (PerspectiveType): The coordinate perspective for calculations.
            Options include 'Apparent Geocentric', 'True Geocentric', 'Heliocentric',
            or 'Topocentric'. Defaults to 'Apparent Geocentric'.
        custom_ayanamsa_t0 (Optional[float]): Reference epoch (Julian Day) for user-defined
            ayanamsa. Only used when sidereal_mode is 'USER'. Defaults to None.
        custom_ayanamsa_ayan_t0 (Optional[float]): Ayanamsa value (degrees) at the
            reference epoch t0. Only used when sidereal_mode is 'USER'. Defaults to None.

    Raises:
        KerykeionException: When invalid configuration combinations are detected,
            such as setting sidereal_mode with tropical zodiac, or using invalid
            enumeration values.

    Example:
        >>> config = ChartConfiguration(
        ...     zodiac_type="Sidereal",
        ...     sidereal_mode="LAHIRI",
        ...     houses_system_identifier="K",
        ...     perspective_type="Topocentric"
        ... )
    r­   Nr¯   Úhouses_system_identifierr¨   r²   r³   c                 ó$   — | j                  «        y rx   )Úvalidate©Úselfs    r~   Ú__post_init__z ChartConfiguration.__post_init__O  s   € Ø�‰�r€   c                 ód  — 	 t        | j                  «      }|| j                  k7  r|| _        	 | j
                  r| j                  dk(  rt        d«      ‚| j                  dk(  r¢| j
                  s!t        | _        t        j                  d«       nC| j
                  t        t        «      vr(t        d| j
                  › dt        t        «      › �«      ‚| j
                  dk(  r#| j                  �| j                  €t        d	«      ‚| j                  t        t        «      vr(t        d| j                  › d
t        t        «      › �«      ‚| j                  t        t         «      vr(t        d| j                  › dt        t         «      › �«      ‚y# t        $ r}t        t	        |«      «      |‚d}~ww xY w)aØ  
        Validate configuration settings for internal consistency.

        Performs comprehensive validation of all configuration parameters to ensure
        they form a valid, compatible combination. This includes checking enumeration
        values, zodiac/sidereal mode compatibility, and setting defaults where needed.

        Raises:
            KerykeionException: If any configuration parameter is invalid or if
                incompatible parameter combinations are detected.

        Side Effects:
            - Sets default sidereal_mode to FAGAN_BRADLEY if zodiac_type is Sidereal
              and no sidereal_mode is specified
            - Logs informational message when setting default sidereal mode
        Nr$   z:You can't set a sidereal mode with a Tropical zodiac type!r¡   z1No sidereal mode set, using default FAGAN_BRADLEYú'z5' is not a valid sidereal mode! Available modes are: r¢   zžSidereal mode 'USER' requires both custom_ayanamsa_t0 (reference epoch as Julian Day) and custom_ayanamsa_ayan_t0 (ayanamsa value in degrees at t0) to be set.z6' is not a valid house system! Available systems are: z@' is not a valid chart perspective! Available perspectives are: )r   r­   Ú
ValueErrorr   Ústrr¯   r!   ÚloggingÚinfor
   r   r²   r³   rº   r   r¨   r   )r¾   Únormalized_zodiac_typeÚexcs      r~   r¼   zChartConfiguration.validateR  sÇ  € ð$	:Ü%:¸4×;KÑ;KÓ%LÐ"ð &¨×)9Ñ)9Ò9Ø#9�Õ ð ×Ò $×"2Ñ"2°jÒ"@Ü$Ð%aÓbÐbà×Ñ˜zÒ)Ø×%Ò%Ü%:�Ô"Ü—‘ÐPÕQØ×#Ñ#¬8´LÓ+AÑAÜ(Ø˜×*Ñ*Ð+Ð+`ÔaiÔjvÓawÐ`xÐyóð ð
 ×!Ñ! VÒ+Ø×*Ñ*Ð2°d×6RÑ6RÐ6ZÜ,ðcóð ð ×(Ñ(´Ô9OÓ0PÑPÜ$Ø�D×1Ñ1Ð2Ð2hÔiqô  sIó  jJð  iKð  Lóð ð
 × Ñ ¬´Ó(AÑAÜ$Ø�D×)Ñ)Ð*Ð*jÔksô  uDó  lEð  kFð  Góð ð BøôE ò 	8Ü$¤S¨£XÓ.°CÐ7ûð	8ús   ‚F Æ	F/ÆF*Æ*F/©r’   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r%   r­   r   Ú__annotations__r¯   r   r   r#   rº   r   r&   r¨   r   r²   Úfloatr³   r¿   r¼   ry   r€   r~   r™   r™      sb   … ñ$ðL 2€K�Ó1Ø,0€M�8˜LÑ)Ó0Ø7WÐÐ4ÓWØ(@Ð�oÓ@Ø*.Ð˜ ™Ó.Ø/3Ð˜X e™_Ó3óô9r€   c                   ó®   — e Zd ZU dZdZeed<   dZeed<   dZe	ed<   dZ
e	ed	<   d
Zeed<   dZee	   ed<    ee¬«      Zeeef   ed<   dededdfd„Zdd„Zy)ÚLocationDataaÆ  
    Information about a geographical location for astrological calculations.

    This class handles all location-related data including coordinates, timezone
    information, and interaction with the GeoNames API for automatic location
    data retrieval. It provides methods for fetching location data online and
    preparing coordinates for astrological calculations.

    Attributes:
        city (str): Name of the city or location. Defaults to "Greenwich".
        nation (str): ISO country code (2-letter). Defaults to "GB" (United Kingdom).
        lat (float): Latitude in decimal degrees. Positive for North, negative for South.
            Defaults to 51.5074 (Greenwich).
        lng (float): Longitude in decimal degrees. Positive for East, negative for West.
            Defaults to 0.0 (Greenwich).
        tz_str (str): IANA timezone identifier (e.g., 'Europe/London', 'America/New_York').
            Defaults to "Etc/GMT".
        altitude (Optional[float]): Altitude above sea level in meters. Used for
            topocentric calculations. Defaults to None (sea level assumed).
        city_data (Dict[str, str]): Raw data retrieved from GeoNames API. Used internally
            for caching and validation. Defaults to empty dictionary.

    Note:
        When using online mode, the initial coordinate and timezone values may be
        overridden by data fetched from the GeoNames API based on city and nation.
        For polar regions, latitude values are automatically adjusted to prevent
        calculation errors.

    Example:
        >>> location = LocationData(city="Rome", nation="IT")
        >>> location.fetch_from_geonames("your_username", 30)
        >>> location.prepare_for_calculation()
    Ú	GreenwichÚcityÚGBÚnationçÅþ²{òÀI@r›   r    rš   úEtc/GMTÚtz_strNÚaltitude)Údefault_factoryÚ	city_dataÚusernameÚcache_expire_after_daysr’   c                 ó&  — t        j                  d| j                  › d| j                  › d�«       t	        | j                  | j                  ||¬«      }|j                  «       | _        g d¢}|D �cg c]  }|| j                  vsŒ|‘Œ }}|rt        ddj                  |«      › d�«      ‚| j                  d   | _        t        | j                  d	   «      | _
        t        | j                  d
   «      | _        | j                  d   | _        yc c}w )a�  
        Fetch location data from GeoNames API.

        Retrieves accurate coordinates, timezone, and country code information
        for the specified city and country from the GeoNames web service.
        Updates the instance attributes with the fetched data.

        Args:
            username (str): GeoNames API username. Must be registered at geonames.org.
                Free accounts are limited to 2000 requests per hour.
            cache_expire_after_days (int): Number of days to cache the location data
                locally before refreshing from the API.

        Raises:
            KerykeionException: If required data is missing from the API response,
                typically due to network issues, invalid location names, or API limits.

        Side Effects:
            - Updates city_data with raw API response
            - Updates nation, lng, lat, and tz_str with fetched values
            - May create or update local cache files

        Note:
            The method validates that all required fields (countryCode, timezonestr,
            lat, lng) are present in the API response before updating instance attributes.
        z"Fetching timezone/coordinates for z, z from geonames©rÛ   rÜ   )ÚcountryCodeÚtimezonestrr›   rš   zMissing data from geonames: z4. Check your connection or try a different location.rß   rš   r›   rà   N)rÄ   rÅ   rÒ   rÔ   r   Úget_serialized_datarÚ   r   ÚjoinrÎ   rš   r›   r×   )r¾   rÛ   rÜ   ÚgeonamesÚrequired_fieldsr   Úmissing_fieldss          r~   Úfetch_from_geonamesz LocationData.fetch_from_geonames¼  sý   € ô6 	�‰Ð9¸$¿)¹)¸ÀBÀtÇ{Á{ÀmÐSaÐbÔcä Ø�I‰I�t—{‘{¨XÐOfô
ˆð "×5Ñ5Ó7ˆŒò GˆØ-<Ö\ EÀÈTÏ^É^Ò@[š%Ð\ˆÐ\áÜ$Ø.¨t¯y©y¸Ó/HÐ.Ið JEð Eóð ð —n‘n ]Ñ3ˆŒÜ˜Ÿ™¨Ñ.Ó/ˆŒÜ˜Ÿ™¨Ñ.Ó/ˆŒØ—n‘n ]Ñ3ˆ�ùò ]s   Á1DÂDc                 ó8   — t        | j                  «      | _        y)uæ  
        Prepare location data for astrological calculations.

        Performs final adjustments to location data to ensure compatibility
        with Swiss Ephemeris calculations. This includes handling special cases
        like polar regions where extreme latitudes can cause calculation errors.

        Side Effects:
            - Adjusts latitude values for polar regions (beyond Â±66.5Â°) to
              prevent Swiss Ephemeris calculation failures
            - May log warnings about latitude adjustments

        Note:
            This method should be called after all location data has been set,
            either manually or via fetch_from_geonames(), and before performing
            any astrological calculations.
        N)r   r›   r½   s    r~   Úprepare_for_calculationz$LocationData.prepare_for_calculationï  s   € ô& 3°4·8±8Ó<ˆ�r€   rÈ   )rÉ   rÊ   rË   rÌ   rÒ   rÃ   rÍ   rÔ   r›   rÎ   rš   r×   rØ   r   r   ÚdictrÚ   r   Úintræ   rè   ry   r€   r~   rÐ   rÐ   Ž  s„   … ñ ðD €Dˆ#ÓØ€FˆCÓØ€CˆÓØ€CˆÓØ€FˆCÓØ $€Hˆh�u‰oÓ$ñ !&°dÔ ;€Iˆt�C˜�H‰~Ó;ð14¨Cð 14È#ð 14ÐRVó 14ôf=r€   rÐ   c            9       óŠ  — e Zd ZdZedddddddddddddedeeeddddddfdddœde	d	e
e   d
e
e   de
e   de
e   de
e   de
e	   de
e	   de
e   de
e   de
e	   de
e	   dedede
e   dededede
e   de
e   de
ee      dede
e   de
e   d ed!ed"ef6d#„«       Zed$d%d&dd'd(eedeeddddddfde	d)e	de	de	de	dededede	dede
e   dedede
e   de
ee      ded!ede
e   de
e   d"ef(d*„«       Zeddddddddedeedddddfde	de
e	   de
e	   de
e   de
e   de
e	   de
e	   dedede
e   dedede
ee      ded!ede
e   de
e   d"ef$d+„«       Zed,ee	ef   d-ed"dfd.„«       Zed,ee	ef   de
ee      d"ee   fd/„«       Zed,ee	ef   d0ed1ed2ed3ed4ee   d5ed6ee   dee   d"dfd7„«       Z ed8ed,ee	ef   d2ed3ed4ee   d5edee   d"dfd9„«       Z!ed2edededed"ef
d:„«       Z"ed;ed<ee	ef   d,ee	ef   d2ed3ed4ee   d5edee   d6ee   d"dfd=„«       Z#e	 dAd,ee	ef   dee   d>e
ee      d"dfd?„«       Z$ed,ee	ef   d"dfd@„«       Z%y)BÚAstrologicalSubjectFactoryu  
    Factory class for creating comprehensive astrological subjects.

    This factory creates AstrologicalSubjectModel instances with complete astrological
    information including planetary positions, house cusps, aspects, lunar phases, and
    various specialized astrological points. It provides multiple class methods for
    different initialization scenarios and supports both online and offline calculation modes.

    The factory handles complex astrological calculations using the Swiss Ephemeris library,
    supports multiple coordinate systems and house systems, and can automatically fetch
    location data from online sources.

    Supported Astrological Points:
        - Traditional Planets: Sun through Pluto
        - Lunar Nodes: Mean and True North/South Nodes
        - Lilith Points: Mean and True Black Moon
        - Asteroids: Ceres, Pallas, Juno, Vesta
        - Centaurs: Chiron, Pholus
        - Trans-Neptunian Objects: Eris, Sedna, Haumea, Makemake, Ixion, Orcus, Quaoar
        - Fixed Stars: 23 stars including all 15 Behenian stars, Royal Stars, and navigational stars
        - Arabic Parts: Pars Fortunae, Pars Spiritus, Pars Amoris, Pars Fidei
        - Special Points: Vertex, Anti-Vertex, Earth (for heliocentric charts)
        - House Cusps: All 12 houses with configurable house systems
        - Angles: Ascendant, Medium Coeli, Descendant, Imum Coeli

    Supported Features:
        - Multiple zodiac systems (Tropical/Sidereal with various ayanamshas)
        - Multiple house systems (Placidus, Koch, Equal, Whole Sign, etc.)
        - Multiple coordinate perspectives (Geocentric, Heliocentric, Topocentric)
        - Automatic timezone and coordinate resolution via GeoNames API
        - Lunar phase calculations
        - Day/night chart detection for Arabic parts
        - Performance optimization through selective point calculation
        - Comprehensive error handling and validation

    Class Methods:
        from_birth_data: Create subject from standard birth data (most flexible)
        from_iso_utc_time: Create subject from ISO UTC timestamp
        from_current_time: Create subject for current moment

    Example:
        >>> # Create natal chart
        >>> subject = AstrologicalSubjectFactory.from_birth_data(
        ...     name="John Doe",
        ...     year=1990, month=6, day=15,
        ...     hour=14, minute=30,
        ...     city="Rome", nation="IT",
        ...     online=True
        ... )
        >>> print(f"Sun: {subject.sun.sign} {subject.sun.abs_pos}Â°")
        >>> print(f"Active points: {len(subject.active_points)}")

        >>> # Create chart for current time
        >>> now_subject = AstrologicalSubjectFactory.from_current_time(
        ...     name="Current Moment",
        ...     city="London", nation="GB"
        ... )

    Thread Safety:
        This factory is not thread-safe due to its use of the Swiss Ephemeris library
        which maintains global state. Use separate instances in multi-threaded applications
        or implement appropriate locking mechanisms.
    ÚNowNTr   F)ÚsecondsÚsuppress_geonames_warningÚnameÚyearÚmonthÚdayÚhourÚminuterÒ   rÔ   rš   r›   r×   Úgeonames_usernameÚonliner­   r¯   rº   r¨   rÜ   Úis_dstrØ   Úactive_pointsÚcalculate_lunar_phaser²   r³   rî   rï   r’   c          	      ó   — |�
|�|�|�|�|€tt        j                  «       }|�|n|j                  }|�|n|j                  }|�|n|j                  }|�|n|j
                  }|�|n|j                  }|�|n|j                  }i }||d<   t        t        j                  «       «      |d<   |€t        t        «      }nt        |«      }||d<   t        ||||||¬«      }|j                  |d<   |j                  |d<   |j                   |d<   |j"                  |d	<   |€6|r4|
r|	r|s.t%        «       }|t&        k(  r|st)        j*                  t,        «       t/        |xs d
|xs d|
�|
nd|	�|	nd|xs d|¬«      }|s|r|
�|	€t1        d«      ‚|r%|r|
�|	€|j3                  |xs
 t%        «       |¬«       |j5                  «        |j6                  |d<   |j8                  |d<   |j:                  |d<   |j<                  |d<   |j>                  |d<   |j@                  |d<   ||d<   ||d<   ||d<   ||d<   ||d<   ||d<   ||d<   tB        jE                  ||«       t        t        tF        «      jH                  jK                  «       dz  «      } tM        | ||d   |d   |d   ¬ «      5 }!|!|d!<   tO        jP                  |j                   jS                  d"«      «      |d#<   tB        jU                  ||«      }"tB        jW                  |d$   |d   |d   |jY                  d«      xs d%¬&«      |d'<   tB        j[                  |||"«       |j                  d(k(  r#	 tO        j\                  |d$   |!«      }#|#d)   |d*<   nd|d*<   ddd«       tB        ja                  |«       |r2d,|v r.d-|v r*tc        |d,   jd                  |d-   jd                  «      |d.<   nd|d.<   tg        d/i |¤ŽS # t^        $ r'}$t)        j*                  d+|$› �«       d|d*<   Y d}$~$ŒŒd}$~$ww xY w# 1 sw Y   Œ•xY w)0aC  
        Create an astrological subject from standard birth or event data.

        This is the most flexible and commonly used factory method. It creates a complete
        astrological subject with planetary positions, house cusps, and specialized points
        for a specific date, time, and location. Supports both online location resolution
        and offline calculation modes.

        Args:
            name (str, optional): Name or identifier for the subject. Defaults to "Now".
            year (int, optional): Year of birth/event. Defaults to current year.
            month (int, optional): Month of birth/event (1-12). Defaults to current month.
            day (int, optional): Day of birth/event (1-31). Defaults to current day.
            hour (int, optional): Hour of birth/event (0-23). Defaults to current hour.
            minute (int, optional): Minute of birth/event (0-59). Defaults to current minute.
            seconds (int, optional): Seconds of birth/event (0-59). Defaults to 0.
            city (str, optional): City name for location lookup. Used with online=True.
                Defaults to None (Greenwich if not specified).
            nation (str, optional): ISO country code (e.g., 'US', 'GB', 'IT'). Used with
                online=True. Defaults to None ('GB' if not specified).
            lng (float, optional): Longitude in decimal degrees. East is positive, West
                is negative. If not provided and online=True, fetched from GeoNames.
            lat (float, optional): Latitude in decimal degrees. North is positive, South
                is negative. If not provided and online=True, fetched from GeoNames.
            tz_str (str, optional): IANA timezone identifier (e.g., 'Europe/London').
                If not provided and online=True, fetched from GeoNames.
            geonames_username (str, optional): Username for GeoNames API. Required for
                online location lookup. Get one free at geonames.org.
            online (bool, optional): Whether to fetch location data online. If False,
                lng, lat, and tz_str must be provided. Defaults to True.
            zodiac_type (ZodiacType, optional): Zodiac system - 'Tropical' or 'Sidereal'.
                Defaults to 'Tropical'.
            sidereal_mode (SiderealMode, optional): Sidereal calculation mode (e.g.,
                'FAGAN_BRADLEY', 'LAHIRI'). Only used with zodiac_type='Sidereal'.
            houses_system_identifier (HousesSystemIdentifier, optional): House system
                for cusp calculations (e.g., 'P'=Placidus, 'K'=Koch, 'E'=Equal).
                Defaults to 'P' (Placidus).
            perspective_type (PerspectiveType, optional): Calculation perspective:
                - 'Apparent Geocentric': Standard geocentric with light-time correction
                - 'True Geocentric': Geometric geocentric positions
                - 'Heliocentric': Sun-centered coordinates
                - 'Topocentric': Earth surface perspective (requires altitude)
                Defaults to 'Apparent Geocentric'.
            cache_expire_after_days (int, optional): Days to cache GeoNames data locally.
                Defaults to 30.
            is_dst (bool, optional): Daylight Saving Time flag for ambiguous times.
                If None, pytz attempts automatic detection. Set explicitly for
                times during DST transitions.
            altitude (float, optional): Altitude above sea level in meters. Used for
                topocentric calculations and atmospheric corrections. Defaults to None
                (sea level assumed).
            active_points (Optional[List[AstrologicalPoint]], optional): List of astrological
                points to calculate. Omitting points can improve performance for
                specialized applications. If None, uses DEFAULT_ACTIVE_POINTS.
            calculate_lunar_phase (bool, optional): Whether to calculate lunar phase.
                Requires Sun and Moon in active_points. Defaults to True.
            custom_ayanamsa_t0 (float, optional): Reference epoch as a Julian Day
                for the USER sidereal mode. This is the date when the tropical and
                sidereal zodiacs are considered to coincide (ayanamsa = 0). Required
                when ``sidereal_mode="USER"``. Defaults to None.
            custom_ayanamsa_ayan_t0 (float, optional): Ayanamsa value in degrees at
                the reference epoch ``t0`` for the USER sidereal mode. This is the
                angular offset between tropical 0 Aries and sidereal 0 Aries at
                ``t0``. Required when ``sidereal_mode="USER"``. Defaults to None.
            suppress_geonames_warning (bool, optional): If True, suppresses the warning
                message when using the default GeoNames username. Useful for testing
                or automated processes. Defaults to False.

        Returns:
            AstrologicalSubjectModel: Complete astrological subject with calculated
                positions, houses, and metadata. Access planetary positions via
                attributes like .sun, .moon, .mercury, etc.

        Raises:
            KerykeionException:
                - If offline mode is used without required location data
                - If invalid zodiac/sidereal mode combinations are specified
                - If GeoNames data is missing or invalid
                - If timezone localization fails (ambiguous DST times)

        Examples:
            >>> # Basic natal chart with online location lookup
            >>> chart = AstrologicalSubjectFactory.from_birth_data(
            ...     name="Jane Doe",
            ...     year=1985, month=3, day=21,
            ...     hour=15, minute=30,
            ...     city="Paris", nation="FR",
            ...     geonames_username="your_username"
            ... )

            >>> # Offline calculation with manual coordinates
            >>> chart = AstrologicalSubjectFactory.from_birth_data(
            ...     name="John Smith",
            ...     year=1990, month=12, day=25,
            ...     hour=0, minute=0,
            ...     lng=-74.006, lat=40.7128, tz_str="America/New_York",
            ...     online=False
            ... )

            >>> # Sidereal chart with specific points
            >>> chart = AstrologicalSubjectFactory.from_birth_data(
            ...     name="Vedic Chart",
            ...     year=2000, month=6, day=15, hour=12,
            ...     city="Mumbai", nation="IN",
            ...     zodiac_type="Sidereal",
            ...     sidereal_mode="LAHIRI",
            ...     active_points=["Sun", "Moon", "Mercury", "Venus", "Mars",
            ...                   "Jupiter", "Saturn", "Ascendant"]
            ... )

            >>> # User-defined ayanamsa (v5.12 -- custom sidereal mode)
            >>> chart = AstrologicalSubjectFactory.from_birth_data(
            ...     name="Custom Ayanamsa",
            ...     year=2000, month=1, day=1, hour=0,
            ...     lng=0.0, lat=51.5, tz_str="Etc/GMT", online=False,
            ...     zodiac_type="Sidereal",
            ...     sidereal_mode="USER",
            ...     custom_ayanamsa_t0=2451545.0,   # J2000.0 epoch
            ...     custom_ayanamsa_ayan_t0=23.5,    # 23.5 deg offset at epoch
            ... )

        Note:
            - For high-precision calculations, consider providing seconds parameter
            - Use topocentric perspective for observer-specific calculations
            - Some Arabic parts automatically activate required base points
            - The method handles polar regions by adjusting extreme latitudes
            - Time zones are handled with full DST awareness via pytz
        Nrð   Újson_dirrù   )r­   r¯   rº   r¨   r²   r³   r­   r¯   rº   r¨   rÑ   rÓ   rÕ   r    rÖ   )rÒ   rÔ   r›   rš   r×   rØ   zOFor offline mode, you must provide timezone (tz_str) and coordinates (lat, lng)rÞ   rÒ   rÔ   r›   rš   r×   rØ   rñ   rò   ró   rô   rõ   rî   rø   Úsweph)r—   r˜   rš   r›   rœ   Ú_iflagÚasciiÚhouses_system_nameÚ
julian_dayr   )r  r›   rš   rØ   Ú
is_diurnalr¡   r*   Úayanamsa_valuez$Could not calculate ayanamsa value: r}   r|   Úlunar_phasery   )4r   Únowrñ   rò   ró   rô   rõ   ÚsecondrÃ   r   ÚhomeÚlistr   r™   r­   r¯   rº   r¨   r–   r•   rÄ   ÚwarningÚ!GEONAMES_DEFAULT_USERNAME_WARNINGrÐ   r   ræ   rè   rÒ   rÔ   r›   rš   r×   rØ   rì   Ú_calculate_time_conversionsÚ__file__ÚparentÚabsoluter¸   r¤   Ú
house_nameÚencodeÚ_calculate_housesÚ_compute_is_diurnalÚgetÚ_calculate_planetsÚget_ayanamsa_ex_utÚ	ExceptionÚ_calculate_day_of_weekr   Úabs_posr   )%Úclsrð   rñ   rò   ró   rô   rõ   rÒ   rÔ   rš   r›   r×   rö   r÷   r­   r¯   rº   r¨   rÜ   rø   rØ   rù   rú   r²   r³   rî   rï   r  Ú	calc_dataÚactive_points_listr˜   Úlocationr—   r¶   Úcalculated_axial_cuspsÚayan_resultÚes%                                        r~   Úfrom_birth_dataz*AstrologicalSubjectFactory.from_birth_dataF  s�  € ð@ ˆ<˜5˜=¨C¨K¸4¸<È6È>Ð]dÐ]lÜ—,‘,“.ˆCØÐ+‘4°·±ˆDØ"Ð.‘E°C·I±IˆEØ˜‘#¨c¯g©gˆCØÐ+‘4°·±ˆDØ%Ð1‘V°s·z±zˆFØ!(Ð!4‘g¸#¿*¹*ˆGð %'ˆ	ð !ˆ	�&ÑÜ #¤D§I¡I£KÓ 0ˆ	�*Ñð Ð Ü:>Ô?TÓ:UÑä!% mÓ!4Ðà%7ˆ	�/Ñ"ô $Ø#Ø'Ø%=Ø-Ø1Ø$;ô
ˆð $*×#5Ñ#5ˆ	�-Ñ Ø%+×%9Ñ%9ˆ	�/Ñ"Ø06×0OÑ0Oˆ	Ð,Ñ-Ø(.×(?Ñ(?ˆ	Ð$Ñ%ð Ð$©¹ÁCÉvÜ 6Ó 8ÐØ Ô$=Ò=ÑF_Ü—‘Ô AÔBô  ØÒ$˜Ø’>˜TØ�‘¨GØ�‘¨CØÒ&˜YØô
ˆñ ™v¨¨¸¸Ü$Ð%vÓwÐwñ ™6 S [°C°KØ×(Ñ(Ø*ÒFÔ.DÓ.FÐ`wð )ô ð
 	×(Ñ(Ô*ð %ŸM™Mˆ	�&ÑØ&Ÿo™oˆ	�(ÑØ#Ÿ<™<ˆ	�%ÑØ#Ÿ<™<ˆ	�%ÑØ&Ÿo™oˆ	�(ÑØ (× 1Ñ 1ˆ	�*Ñð !ˆ	�&ÑØ"ˆ	�'ÑØˆ	�%ÑØ ˆ	�&ÑØ$ˆ	�(ÑØ&ˆ	�)ÑØ$ˆ	�(Ñô 	#×>Ñ>¸yÈ(ÔSäœœX›×-Ñ-×6Ñ6Ó8¸7ÑBÓCˆ	ÜØØØ˜%Ñ Ø˜%Ñ Ø˜*Ñ%ô
ð  	3ð Ø"'ˆI�hÑä.1¯n©n¸V×=\Ñ=\×=cÑ=cÐdkÓ=lÓ.mˆIÐ*Ñ+Ü%?×%QÑ%QÐR[Ð]oÓ%pÐ"ô 'A×&TÑ&TØ$ \Ñ2Ø˜eÑ$Ø˜eÑ$Ø"Ÿ™ zÓ2Ò7°að	 'Uó 'ˆI�lÑ#ô '×9Ñ9¸)ÐEWÐYoÔpð ×!Ñ! ZÒ/ð7Ü"%×"8Ñ"8¸À<Ñ9PÐRWÓ"X�KØ2=¸a±.�IÐ.Ò/ð
 /3�	Ð*Ñ+÷A 	3ôD 	#×9Ñ9¸)ÔDñ ! V¨yÑ%8¸UÀiÑ=OÜ';Ø˜&Ñ!×)Ñ)Ø˜%Ñ ×(Ñ(ó(ˆI�mÒ$ð
 (,ˆI�mÑ$ô (Ñ4¨)Ñ4Ð4øô% !ò 7Ü—O‘OÐ&JÈ1È#Ð$NÔOØ26�IÐ.Ö/ûð7ú÷9 	3ð  	3ús7   ÊB+PÍ	!OÍ*PÏ	PÏO<Ï7PÏ<PÐPÐPrÑ   rÓ   rÖ   r    rÕ   Úiso_utc_timec                 óL  — t        j                  |j                  dd«      «      }|rs|	t        k7  r|	n	t	        «       }|t        k(  r|st        j                  t        «       t        |||¬«      }|j                  «       }t        |d   «      }t        |d   «      }t        j                  |«      }|j                  |«      }| j                  ||j                  |j                   |j"                  |j$                  |j&                  |j(                  |||||d|	|
|||||||||¬«      S )a,  
        Create an astrological subject from an ISO formatted UTC timestamp.

        This method is ideal for creating astrological subjects from standardized
        time formats, such as those stored in databases or received from APIs.
        It automatically handles timezone conversion from UTC to the specified
        local timezone.

        Args:
            name (str): Name or identifier for the subject.
            iso_utc_time (str): ISO 8601 formatted UTC timestamp. Supported formats:
                - "2023-06-15T14:30:00Z" (with Z suffix)
                - "2023-06-15T14:30:00+00:00" (with UTC offset)
                - "2023-06-15T14:30:00.123Z" (with milliseconds)
            city (str, optional): City name for location. Defaults to "Greenwich".
            nation (str, optional): ISO country code. Defaults to "GB".
            tz_str (str, optional): IANA timezone identifier for result conversion.
                The ISO time is assumed to be in UTC and will be converted to this
                timezone. Defaults to "Etc/GMT".
            online (bool, optional): Whether to fetch coordinates online. If True,
                coordinates are fetched via GeoNames API. Defaults to True.
            lng (float, optional): Longitude in decimal degrees. Used when online=False
                or as fallback. Defaults to 0.0 (Greenwich).
            lat (float, optional): Latitude in decimal degrees. Used when online=False
                or as fallback. Defaults to 51.5074 (Greenwich).
            geonames_username (str, optional): GeoNames API username. Required when
                online=True. Defaults to DEFAULT_GEONAMES_USERNAME.
            zodiac_type (ZodiacType, optional): Zodiac system. Defaults to 'Tropical'.
            sidereal_mode (SiderealMode, optional): Sidereal mode when zodiac_type
                is 'Sidereal'. Defaults to None.
            houses_system_identifier (HousesSystemIdentifier, optional): House system.
                Defaults to 'P' (Placidus).
            perspective_type (PerspectiveType, optional): Calculation perspective.
                Defaults to 'Apparent Geocentric'.
            altitude (float, optional): Altitude in meters for topocentric calculations.
                Defaults to None (sea level).
            active_points (Optional[List[AstrologicalPoint]], optional): Points to calculate.
                If None, uses DEFAULT_ACTIVE_POINTS.
            calculate_lunar_phase (bool, optional): Whether to calculate lunar phase.
                Defaults to True.
            suppress_geonames_warning (bool, optional): Suppress GeoNames default
                username warning. Defaults to False.
            custom_ayanamsa_t0 (float, optional): Reference epoch (Julian Day) for
                the USER sidereal mode -- the date when tropical and sidereal zodiacs
                coincide. Required when ``sidereal_mode="USER"``. Defaults to None.
            custom_ayanamsa_ayan_t0 (float, optional): Ayanamsa offset in degrees at
                epoch ``t0`` for the USER sidereal mode. Required when
                ``sidereal_mode="USER"``. Defaults to None.

        Returns:
            AstrologicalSubjectModel: Astrological subject with positions calculated
                for the specified UTC time converted to local timezone.

        Raises:
            ValueError: If the ISO timestamp format is invalid or cannot be parsed.
            KerykeionException: If location data cannot be fetched or is invalid.

        Examples:
            >>> # From API timestamp with online location lookup
            >>> subject = AstrologicalSubjectFactory.from_iso_utc_time(
            ...     name="Event Chart",
            ...     iso_utc_time="2023-12-25T12:00:00Z",
            ...     city="Tokyo", nation="JP",
            ...     tz_str="Asia/Tokyo",
            ...     geonames_username="your_username"
            ... )

            >>> # From database timestamp with manual coordinates
            >>> subject = AstrologicalSubjectFactory.from_iso_utc_time(
            ...     name="Historical Event",
            ...     iso_utc_time="1969-07-20T20:17:00Z",
            ...     lng=-95.0969, lat=37.4419,  # Houston
            ...     tz_str="America/Chicago",
            ...     online=False
            ... )

        Note:
            - The method assumes the input timestamp is in UTC
            - Local time conversion respects DST rules for the target timezone
            - Milliseconds in the timestamp are supported but truncated to seconds
            - When online=True, the city/nation parameters override lng/lat
        ÚZz+00:00)rÛ   rš   r›   F)rð   rñ   rò   ró   rô   rõ   rî   rÒ   rÔ   rš   r›   r×   r÷   rö   r­   r¯   rº   r¨   rØ   rù   rú   rï   r²   r³   )r   ÚfromisoformatÚreplacer•   r–   rÄ   r	  r
  r   rá   rÎ   ÚpytzÚtimezoneÚ
astimezoner   rñ   rò   ró   rô   rõ   r  )r  rð   r!  rÒ   rÔ   r×   r÷   rš   r›   rö   r­   r¯   rº   r¨   rØ   rù   rú   rï   r²   r³   ÚdtÚresolved_usernamerã   rÚ   Ú
local_timeÚlocal_datetimes                             r~   Úfrom_iso_utc_timez,AstrologicalSubjectFactory.from_iso_utc_timep  s>  € ôT ×#Ñ# L×$8Ñ$8¸¸hÓ$GÓHˆñ à%6Ô:SÒ%SÑ!ÔYoÓYqð ð !Ô$=Ò=ÑF_Ü—‘Ô AÔBä$ØØØ*ôˆHð !×4Ñ4Ó6ˆIÜ˜	 %Ñ(Ó)ˆCÜ˜	 %Ñ(Ó)ˆCô —]‘] 6Ó*ˆ
ØŸ™ zÓ2ˆð ×"Ñ"ØØ×$Ñ$Ø ×&Ñ&Ø×"Ñ"Ø×$Ñ$Ø!×(Ñ(Ø"×)Ñ)ØØØØØØØ/Ø#Ø'Ø%=Ø-ØØ'Ø"7Ø&?Ø1Ø$;ð1 #ó 
ð 	
r€   c                 óò   — t        j                  «       }| j                  ||j                  |j                  |j
                  |j                  |j                  |j                  ||||||||	|
|||||||¬«      S )a,  
        Create an astrological subject for the current moment in time.

        This convenience method creates a "now" chart, capturing the current
        astrological conditions at the moment of execution. Useful for horary
        astrology, electional astrology, or real-time astrological monitoring.

        Args:
            name (str, optional): Name for the current moment chart.
                Defaults to "Now".
            city (str, optional): City name for location lookup. If not provided
                and online=True, defaults to Greenwich.
            nation (str, optional): ISO country code. If not provided and
                online=True, defaults to 'GB'.
            lng (float, optional): Longitude in decimal degrees. If not provided
                and online=True, fetched from GeoNames API.
            lat (float, optional): Latitude in decimal degrees. If not provided
                and online=True, fetched from GeoNames API.
            tz_str (str, optional): IANA timezone identifier. If not provided
                and online=True, fetched from GeoNames API.
            geonames_username (str, optional): GeoNames API username for location
                lookup. Required when online=True and location is not fully specified.
            online (bool, optional): Whether to fetch location data online.
                Defaults to True.
            zodiac_type (ZodiacType, optional): Zodiac system to use.
                Defaults to 'Tropical'.
            sidereal_mode (SiderealMode, optional): Sidereal calculation mode.
                Only used when zodiac_type is 'Sidereal'. Defaults to None.
            houses_system_identifier (HousesSystemIdentifier, optional): House
                system for calculations. Defaults to 'P' (Placidus).
            perspective_type (PerspectiveType, optional): Calculation perspective.
                Defaults to 'Apparent Geocentric'.
            active_points (Optional[List[AstrologicalPoint]], optional): Astrological points
                to calculate. If None, uses DEFAULT_ACTIVE_POINTS.
            calculate_lunar_phase (bool, optional): Whether to calculate lunar phase.
                Defaults to True.
            suppress_geonames_warning (bool, optional): Suppress GeoNames default
                username warning. Defaults to False.
            custom_ayanamsa_t0 (float, optional): Reference epoch (Julian Day) for
                the USER sidereal mode. Required when ``sidereal_mode="USER"``.
                Defaults to None.
            custom_ayanamsa_ayan_t0 (float, optional): Ayanamsa offset in degrees at
                epoch ``t0`` for the USER sidereal mode. Required when
                ``sidereal_mode="USER"``. Defaults to None.

        Returns:
            AstrologicalSubjectModel: Astrological subject representing current
                astrological conditions at the specified or default location.

        Raises:
            KerykeionException: If online location lookup fails or if offline mode
                is used without sufficient location data.

        Examples:
            >>> # Current moment for your location
            >>> now_chart = AstrologicalSubjectFactory.from_current_time(
            ...     name="Current Transits",
            ...     city="New York", nation="US",
            ...     geonames_username="your_username"
            ... )

            >>> # Horary chart with specific coordinates
            >>> horary = AstrologicalSubjectFactory.from_current_time(
            ...     name="Horary Question",
            ...     lng=-0.1278, lat=51.5074,  # London
            ...     tz_str="Europe/London",
            ...     online=False
            ... )

            >>> # Current sidereal positions
            >>> sidereal_now = AstrologicalSubjectFactory.from_current_time(
            ...     name="Sidereal Now",
            ...     city="Mumbai", nation="IN",
            ...     zodiac_type="Sidereal",
            ...     sidereal_mode="LAHIRI"
            ... )

        Note:
            - The exact time is captured at method execution, including seconds
            - For horary astrology, consider the moment of understanding the question
            - System clock accuracy affects precision; ensure accurate system time
            - Time zone detection is automatic when using online location lookup
        )rð   rñ   rò   ró   rô   rõ   rî   rÒ   rÔ   rš   r›   r×   rö   r÷   r­   r¯   rº   r¨   rù   rú   rï   r²   r³   )	r   r  r   rñ   rò   ró   rô   rõ   r  )r  rð   rÒ   rÔ   rš   r›   r×   rö   r÷   r­   r¯   rº   r¨   rù   rú   rï   r²   r³   r  s                      r~   Úfrom_current_timez,AstrologicalSubjectFactory.from_current_time  s…   € ôP �l‰l‹nˆà×"Ñ"ØØ—‘Ø—)‘)Ø—‘Ø—‘Ø—:‘:Ø—J‘JØØØØØØ/ØØ#Ø'Ø%=Ø-Ø'Ø"7Ø&?Ø1Ø$;ð/ #ó 
ð 	
r€   Údatar  c           	      ó  — t        j                  |j                  «      }t        | d   | d   | d   | d   | d   | d   «      }	 |j	                  || j                  d«      ¬«      }|j                  t         j                  «      }|j                  «       | d<   |j                  «       | d<   t        |«      | d<   y# t         j                  j                  $ r t        d	«      ‚t         j                  j                  $ r t        d
«      ‚w xY w)aå  
        Calculate time conversions between local time, UTC, and Julian Day Number.

        Handles timezone-aware conversion from local civil time to UTC and astronomical
        Julian Day Number, including proper DST handling and timezone localization.

        Args:
            data (Dict[str, Any]): Calculation data dictionary containing time components
                (year, month, day, hour, minute, seconds) and optional DST flag.
            location (LocationData): Location data containing timezone information.

        Raises:
            KerykeionException: If DST ambiguity occurs during timezone transitions
                and is_dst parameter is not explicitly set to resolve the ambiguity.

        Side Effects:
            Updates data dictionary with:
            - iso_formatted_utc_datetime: ISO 8601 UTC timestamp
            - iso_formatted_local_datetime: ISO 8601 local timestamp
            - julian_day: Julian Day Number for astronomical calculations

        Note:
            During DST transitions, times may be ambiguous (fall back) or non-existent
            (spring forward). The method raises an exception for ambiguous times unless
            the is_dst parameter is explicitly set to True or False.
        rñ   rò   ró   rô   rõ   rî   rø   )rø   ztAmbiguous time error! The time falls during a DST transition. Please specify is_dst=True or is_dst=False to clarify.zuNon-existent time error! The time does not exist due to DST transition (spring forward). Please specify a valid time.Úiso_formatted_utc_datetimeÚiso_formatted_local_datetimer  N)r&  r'  r×   r   Úlocalizer  Ú
exceptionsÚAmbiguousTimeErrorr   ÚNonExistentTimeErrorr(  ÚutcÚ	isoformatr   )r0  r  Úlocal_timezoneÚnaive_datetimer,  Úutc_datetimes         r~   r  z6AstrologicalSubjectFactory._calculate_time_conversions’  s  € ô: Ÿ™ x§¡Ó7ˆÜ!Ø�‰L˜$˜w™-¨¨e©°d¸6±lÀDÈÁNÐTXÐYbÑTcó
ˆð	Ø+×4Ñ4°^ÈDÏHÉHÐU]ÓL^Ð4Ó_ˆNð &×0Ñ0´·±Ó:ˆØ-9×-CÑ-CÓ-EˆÐ)Ñ*Ø/=×/GÑ/GÓ/IˆÐ+Ñ,ô 0°Ó=ˆˆ\Òøô# �‰×1Ñ1ò 	Ü$ðIóð ô �‰×3Ñ3ò 	Ü$ð/óð ð	ús   Á"B9 Â9AD	c           	      óº  ‡— dt         dt        fˆfd„}g }t        j                  | d   | d   | d   t        j                  | d   «      | d   ¬	«      \  }}}}|| d
<   g d¢}d}	t        |«      D ]   \  }
\  }}t        ||
   ||	||
   ¬«      | |<   Œ" t        t        t        «      «      | d<   d}	 |d«      rWt        |d   d|	|d   ¬«      | d<   t        | d   j                  | d
   «      | d   _        d| d   _        |j                  d«        |d«      rWt        |d   d|	|d   ¬«      | d<   t        | d   j                  | d
   «      | d   _        d| d   _        |j                  d«        |d«      rpt!        j"                  |d   dz   d«      }t        |d|	|d   ¬«      | d<   t        | d   j                  | d
   «      | d   _        d| d   _        |j                  d«        |d«      rpt!        j"                  |d   dz   d«      }t        |d|	|d   ¬«      | d<   t        | d   j                  | d
   «      | d   _        d| d   _        |j                  d«       |S )aV
  
        Calculate house cusps and angular points (Ascendant, MC, etc.).

        Computes the 12 house cusps using the specified house system and calculates
        the four main angles of the chart. Only calculates angular points that are
        included in the active_points list for performance optimization.

        v5.12 Change -- House Cusp Speeds:
            Uses ``swe.houses_ex2()`` instead of ``swe.houses_ex()`` to obtain cusp
            velocities (degrees/day). The ``speed`` field on each house cusp and
            angular point now contains the real rate at which that cusp moves along
            the ecliptic per day, driven by diurnal rotation and the chart's
            geographic latitude. Useful for primary directions and profection
            techniques.

            ``houses_ex2`` returns 4 tuples: ``(cusps, ascmc, cusps_speed,
            ascmc_speed)``. ``cusps_speed[i]`` is the speed for the i-th house
            cusp; ``ascmc_speed[0]`` is the ASC speed; ``ascmc_speed[1]`` is the
            MC speed.

        Args:
            data (Dict[str, Any]): Calculation data dictionary containing configuration
                and location information. Updated with calculated house and angle data.
            active_points (Optional[List[AstrologicalPoint]]): List of points to calculate.
                If None, all points are calculated. Angular points not in this list
                are skipped for performance.

        Side Effects:
            Updates data dictionary with:
            - House cusp objects: first_house through twelfth_house (with ``speed``)
            - Angular points: ascendant, medium_coeli, descendant, imum_coeli (with ``speed``)
            - houses_names_list: List of all house names
            - _houses_degree_ut: Raw house cusp degrees for internal use

        House Systems Supported:
            All systems supported by Swiss Ephemeris including Placidus, Koch,
            Equal House, Whole Sign, Regiomontanus, Campanus, Topocentric, etc.

        Angular Points Calculated:
            - Ascendant: Eastern horizon point (1st house cusp)
            - Medium Coeli (Midheaven): Southern meridian point (10th house cusp)
            - Descendant: Western horizon point (opposite Ascendant)
            - Imum Coeli: Northern meridian point (opposite Medium Coeli)

        Note:
            House calculations respect the zodiac type (Tropical/Sidereal) and use
            the appropriate Swiss Ephemeris function. Angular points include house
            position, speed (from houses_ex2), and retrograde status (always False
            for angles).
        Úpointr’   c                 ó   •— ‰ xs | ‰v S rx   ry   ©r>  rù   s    €r~   Úshould_calculatezFAstrologicalSubjectFactory._calculate_houses.<locals>.should_calculate  ó   ø€ Ø$Ð$Ò>¨°Ð(>Ð>r€   r  r›   rš   rº   rþ   ©Útjdutr›   ÚlonÚhsysÚflagsÚ_houses_degree_ut))Úfirst_houseÚFirst_House)Úsecond_houseÚSecond_House)Úthird_houseÚThird_House)Úfourth_houseÚFourth_House)Úfifth_houseÚFifth_House)Úsixth_houseÚSixth_House)Úseventh_houseÚSeventh_House)Úeighth_houseÚEighth_House)Úninth_houseÚNinth_House)Útenth_houseÚTenth_House)Úeleventh_houseÚEleventh_House)Útwelfth_houseÚTwelfth_HouseÚHouse©Ú
point_typeÚspeedÚhouses_names_listr   rv   r   Ú	ascendantFÚMedium_Coelir*   Úmedium_coeliÚ
Descendanté´   éh  Ú
descendantÚ
Imum_CoeliÚ
imum_coeli)r   Úboolr¤   Ú
houses_ex2rÃ   r  Ú	enumerater   r  r
   r   r   r  ÚhouseÚ
retrogradeÚappendÚmathÚfmod)r0  rù   rA  r  ÚcuspsÚascmcÚcusps_speedÚascmc_speedÚHOUSE_CONFIGrc  ÚiÚ	attr_namer  Údsc_degÚic_degs    `             r~   r  z,AstrologicalSubjectFactory._calculate_housesÉ  sÃ  ø€ ðp	?Ô$5ð 	?¼$õ 	?ð ;=Ðô 25·±Ø�|Ñ$Ø�U‘Ø�U‘Ü—‘˜DÐ!;Ñ<Ó=Ø�x‘.ô2
Ñ.ˆˆu�k ;ð %*ˆÐ Ñ!ò
ˆð  !(ˆ
Ü*3°LÓ*Aò 	Ñ&ˆAÑ&�	˜:Ü=Ø�a‘˜*°À;ÈqÁ>ôˆD�ŠOð	ô %)¬´&Ó)9Ó$:ˆÐ Ñ!ð )ˆ
ñ ˜KÔ(Ü ?Ø�a‘˜+°*ÀKÐPQÁNô!ˆD�Ñô '7°t¸KÑ7H×7PÑ7PÐRVÐWjÑRkÓ&lˆD�ÑÔ#Ø+0ˆD�ÑÔ(Ø"×)Ñ)¨+Ô6ñ ˜NÔ+Ü#BØ�a‘˜.°ZÀ{ÐSTÁ~ô$ˆD�Ñ ô *:¸$¸~Ñ:N×:VÑ:VÐX\Ð]pÑXqÓ)rˆD�Ñ Ô&Ø.3ˆD�Ñ Ô+Ø"×)Ñ)¨.Ô9ñ ˜LÔ)Ü—i‘i  a¡¨3¡°Ó4ˆGÜ!@Ø˜°*ÀKÐPQÁNô"ˆD�Ñô (8¸¸\Ñ8J×8RÑ8RÐTXÐYlÑTmÓ'nˆD�ÑÔ$Ø,1ˆD�ÑÔ)Ø"×)Ñ)¨,Ô7ñ ˜LÔ)Ü—Y‘Y˜u Q™x¨#™~¨sÓ3ˆFÜ!@Ø˜°À;ÈqÁ>ô"ˆD�Ñô (8¸¸\Ñ8J×8RÑ8RÐTXÐYlÑTmÓ'nˆD�ÑÔ$Ø,1ˆD�ÑÔ)Ø"×)Ñ)¨,Ô7à%Ð%r€   Úplanet_nameÚ	planet_idr  r¶   Úhouses_degree_utrc  Úcalculated_planetsc	                 ó&  — 	 t        j                  |||«      d   }	t        j                  |||t         j                  z  «      d   }
|
d   }t        |	d   |||	d   |¬«      | |j	                  «       <   t        |	d   |«      | |j	                  «          _        |	d   dk  | |j	                  «          _        |j                  |«       y# t        $ r?}t        j                  d|› d|› �«       ||v r|j                  |«       Y d}~yY d}~yd}~ww xY w)aý  
        Calculate a single celestial body's position with comprehensive error handling.

        Computes the position of a single planet, asteroid, or other celestial object
        using Swiss Ephemeris, creates a Kerykeion point object, determines house
        position, and assesses retrograde status. Handles calculation errors gracefully
        by logging and removing failed points from the active list.

        Args:
            data (Dict[str, Any]): Main calculation data dictionary to store results.
            planet_name (AstrologicalPoint): Name identifier for the celestial body.
            planet_id (int): Swiss Ephemeris numerical identifier for the object.
            julian_day (float): Julian Day Number for the calculation moment.
            iflag (int): Swiss Ephemeris calculation flags (perspective, zodiac, etc.).
            houses_degree_ut (List[float]): House cusp degrees for house determination.
            point_type (PointType): Classification of the point type for the object.
            calculated_planets (List[str]): Running list of successfully calculated objects.
            active_points (List[AstrologicalPoint]): Active points list (modified on error).

        Side Effects:
            - Adds calculated object to data dictionary using lowercase planet_name as key
            - Appends planet_name to calculated_planets list on success
            - Removes planet_name from active_points list on calculation failure
            - Logs error messages for calculation failures

        Calculated Properties:
            - Zodiacal position (longitude) in degrees
            - House position based on house cusp positions
            - Retrograde status based on velocity (negative = retrograde)
            - Sign, degree, and minute components

        Error Handling:
            If Swiss Ephemeris calculation fails (e.g., for distant asteroids outside
            ephemeris range), the method logs the error and removes the object from
            active_points to prevent cascade failures.

        Note:
            The method uses the Swiss Ephemeris calc_ut function which returns position
            and velocity data. Retrograde determination is based on the velocity
            component being negative (element index 3).
        r   r*   r.   ©rc  rd  ÚdeclinationzError calculating ú: N)r¤   Úcalc_utÚFLG_EQUATORIALr   Úlowerr   rr  rs  rt  r  rÄ   ÚerrorÚremove)r0  r€  r�  r  r¶   r‚  rc  rƒ  rù   Úplanet_calcÚ	planet_eqr†  r  s                r~   Ú_calculate_single_planetz3AstrologicalSubjectFactory._calculate_single_planet\  s  € ðj	2äŸ+™+ j°)¸UÓCÀAÑFˆKô Ÿ™ J°	¸5Ä3×CUÑCUÑ;UÓVÐWXÑYˆIØ# A™,ˆKô )HØ˜A‘ ¸
È+ÐVWÉ.Ðfqô)ˆD�×"Ñ"Ó$Ñ%ô
 /?¸{È1¹~ÐO_Ó.`ˆD�×"Ñ"Ó$Ñ%Ô+ð 4?¸q±>ÀAÑ3EˆD�×"Ñ"Ó$Ñ%Ô0ð ×%Ñ% kÕ2øäò 	2Ü�M‰MÐ.¨{¨m¸2¸a¸SÐAÔBØ˜mÑ+Ø×$Ñ$ [×1Ñ1ô ,ûð	2ús   ‚CC Ã	DÃ0DÄDr>  c           	      ó`  — | j                  «       }||v ry| dk(  rxt        j                  |d   |d   |d   t        j	                  |d   «      |¬«      \  }}	}}
t        |	d   d||
d   ¬	«      |d
<   t        |	d   |«      |d
   _        d|d
   _        y| t        v r”t        |    }t        j                  |||«      d   }t        j                  |||t        j                  z  «      d   }|d   }t        |d   | ||d   |¬«      ||<   t        |d   |«      ||   _        |d   dk  ||   _        yy)a}  
        Ensure a required point is calculated for Arabic Parts computation.

        If the point is not already in the data dictionary, calculates it using
        the appropriate method (Swiss Ephemeris for planets, houses for Ascendant).

        Args:
            point: The point to ensure is calculated
            data: Main calculation data dictionary
            julian_day: Julian Day Number
            iflag: Swiss Ephemeris calculation flags
            houses_degree_ut: House cusp degrees
            point_type: Classification of the point type
            active_points: List of active points (may be modified)
        Nrv   r  r›   rš   rº   rC  r   rb  rf  Fr*   r.   r…  )rŠ  r¤   rp  rÃ   r  r   r   rr  rs  rQ   rˆ  r‰  )r>  r0  r  r¶   r‚  rc  rù   Ú	point_keyÚ_rx  rz  r�  r�  rŽ  r†  s                  r~   Ú_ensure_point_calculatedz3AstrologicalSubjectFactory._ensure_point_calculated¬  sd  € ð2 —K‘K“Mˆ	Ø˜ÑØð �KÒÜ'*§~¡~Ø˜<Ñ(Ø˜‘KØ˜‘KÜ—Z‘Z Ð%?Ñ @ÓAØô(Ñ$ˆAˆu�a˜ô !@Ø�a‘˜+°*ÀKÐPQÁNô!ˆD�Ñô '7°u¸Q±xÐAQÓ&RˆD�ÑÔ#Ø+0ˆD�ÑÔ(Øð Ô$Ñ$Ü(¨Ñ/ˆIÜŸ+™+ j°)¸UÓCÀAÑFˆKäŸ™ J°	¸5Ä3×CUÑCUÑ;UÓVÐWXÑYˆIØ# A™,ˆKÜ=Ø˜A‘ °*ÀKÐPQÁNÐ`kôˆD�‰Oô %5°[À±^ÐEUÓ$VˆD�‰OÔ!Ø)4°Q©¸!Ñ);ˆD�‰OÕ&ð %r€   c                 ób  — 	 t         j                  t         j                  z  }t        j                  | d|«      d   }|d   }d}|||xs df}||df}	t        j                  | t         j
                  |dd|	«      }
|
d   dk\  S # t        $ r#}t        j                  d|› d�«       Y d}~yd}~ww xY w)	aþ  
        Compute whether the chart is diurnal (day) or nocturnal (night).

        Uses the Sun's geometric altitude above/below the horizon, calculated
        from a tropical geocentric position (independent of the chart's
        zodiac_type or perspective_type settings).

        This ensures correct sect classification even for sidereal or
        heliocentric charts, where data["sun"].abs_pos would be in a different
        coordinate system.

        Args:
            julian_day: Julian Day Number for the chart
            lat: Geographic latitude
            lng: Geographic longitude
            altitude: Geographic altitude (meters above sea level)

        Returns:
            bool: True if diurnal (Sun above horizon), False if nocturnal
        r   r    g      ð?r*   z8Could not compute Sun altitude for sect classification: z$. Defaulting to diurnal (day chart).NT)	r¤   r¦   r§   rˆ  ÚazaltÚECL2HORr  rÄ   r	  )r  r›   rš   rØ   Úsun_tropical_flagsÚsun_calcÚsun_lonÚsun_latÚgeoposÚsun_eclr•  r  s               r~   r  z.AstrologicalSubjectFactory._compute_is_diurnalæ  s´   € ð6	Ü!$§¡´#·-±-Ñ!?ÐÜ—{‘{ :¨qÐ2DÓEÀaÑHˆHØ˜q‘kˆGØˆGà˜3 ¢¨AÐ.ˆFØ ¨Ð-ˆGÜ—I‘I˜j¬#¯+©+°v¸qÀ!ÀWÓMˆEà˜‘8˜q‘=Ð øäò 	Ü�O‰OØJÈ1È#ÐMqÐrôô ûð		ús   ‚A?B Â	B.ÂB)Â)B.Ú	part_namer˜   c	           
      óì  ‡— |d   }	|	D �
cg c]	  }
|
|vsŒ|
‘Œ }}
|r,t        j                  d| › d|› �«       |j                  |«       |	D ]  }t        j	                  |‰|||||«       Œ |	D �
cg c]  }
|
j                  «       ‘Œ }}
t        ˆfd„|D «       «      sy|	D �
cg c]  }
‰|
j                  «          j                  ‘Œ! }}
d|v r#d|v r‰j                  dd	«      }|r|d   n|d   }n|d
   }t        j                   ||Ž d«      }|dk  r|dz  }| j                  «       }t        || |¬«      ‰|<   t        ||«      ‰|   _        d‰|   _        |j                  | «       yc c}
w c c}
w c c}
w )aP  
        Calculate an Arabic Part (Lot) using its configuration.

        This method handles:
        - Auto-activation of required prerequisite points
        - Day/night chart detection using pre-computed is_diurnal value
        - Formula application and result storage

        Args:
            part_name: Name of the Arabic Part to calculate
            config: Configuration dict with required points and formula(s)
            data: Main calculation data dictionary (must contain is_diurnal)
            julian_day: Julian Day Number
            iflag: Swiss Ephemeris calculation flags
            houses_degree_ut: House cusp degrees
            point_type: Classification of the point type
            active_points: List of active points (may be modified)
            calculated_planets: List of successfully calculated points
        r‚   z)Automatically adding required points for r‡  c              3   ó&   •K  — | ]  }|‰v –— Œ
 y ­wrx   ry   )Ú.0Úkr0  s     €r~   ú	<genexpr>zDAstrologicalSubjectFactory._calculate_arabic_part.<locals>.<genexpr>B  s   øè ø€ Ò4 �1˜”9Ñ4ùs   ƒNrƒ   r„   r  Tr‰   rk  r   ©rc  F)rÄ   rÅ   Úextendrì   r“  rŠ  Úallr  r  ru  rv  r   r   rr  rs  rt  )r�  r˜   r0  r  r¶   r‚  rc  rù   rƒ  Úrequired_pointsÚpÚmissing_pointsr>  Úrequired_keysÚ	positionsr  r‰   Úpart_degÚpart_keys     `                r~   Ú_calculate_arabic_partz1AstrologicalSubjectFactory._calculate_arabic_part  sŸ  ø€ ð> ! Ñ,ˆð &5ÖO ¸ÀÒ8Nš!ÐOˆÐOÙÜ�L‰LÐDÀYÀKÈrÐR`ÐQaÐbÔcØ× Ñ  Ô0ð %ò 	ˆEÜ&×?Ñ?Ø�t˜Z¨Ð0@À*Èmõð	ð -<Ö< q˜Ÿ™�Ð<ˆÐ<ÜÓ4 mÔ4Ô4Øð 7FÖF°�T˜!Ÿ'™'›)‘_×,Ó,ÐFˆ	ÐFð ˜FÑ" ¸&Ñ'@ØŸ™ ,°Ó5ˆJÙ/9�f˜]Ò+¸vÀoÑ?V‰Gà˜YÑ'ˆGô —9‘9™W iÐ0°#Ó6ˆØ�aŠ<Ø˜‰OˆHð —?‘?Ó$ˆÜ8¸À9ÐYcÔdˆˆX‰Ü/°Ð:JÓKˆˆX‰ÔØ$)ˆˆX‰Ô!Ø×!Ñ! )Õ,ùòK Pùò =ùò
 Gs   ‹	E'•E'Á/E,Â!$E1r  c                 ó  ‡— dt         dt        fˆfd„}d}| d   }| d   }| d   }g }t        j                  «       D �]h  \  }	}
 ||	«      sŒt        j                  | |	|
|||||‰«	       |	dv rL|	j                  «       }|| v r8t        j                  ||
|t        j                  z  «      d	   }|d
   | |   _
        |	dk(  rîd}|	j                  «       } ||«      rÔ|| v rÐ| |   }t        j                  |j                  dz   d«      }t        ||||j                  �|j                   nd|j                  �|j                   nd¬«      | |j                  «       <   t!        ||«      | |j                  «          _        |j$                  | |j                  «          _        |j'                  |«       |	dk(  s�Œwd}|	j                  «       } ||«      s�Œ“|| v s�Œ™| |   }t        j                  |j                  dz   d«      }t        ||||j                  �|j                   nd|j                  �|j                   nd¬«      | |j                  «       <   t!        ||«      | |j                  «          _        |j$                  | |j                  «          _        |j'                  |«       �Œk t(        j                  «       D ]=  \  }} ||«      sŒ	 t        j                  | |t        j*                  |z   |||||‰«	       Œ? t4        D �]  } ||«      sŒ	 t6        j9                  ||«      }t        j:                  |||«      d	   }|d	   }t=        |«      dkD  r|d   nd}t        j:                  |||t        j                  z  «      d	   }t=        |«      d
kD  r|d
   nd}	 t        j>                  |«      d	   }|j                  «       }t        ||||||¬«      | |<   t!        ||«      | |   _        d| |   _        |j'                  |«       �Œ t@        j                  «       D ]+  \  }} ||«      sŒt        jC                  ||| ||||‰|«	       Œ-  |d«      s |d«      rè	 t        jD                  | d   | d   | d   tF        jI                  d «      |¬!«      \  } }!|!d   }" |d«      r@t        |"d|¬"«      | d#<   t!        |"|«      | d#   _        d| d#   _        |j'                  d«        |d«      rYt        j                  |"dz   d«      }#t        |#d|¬"«      | d$<   t!        |#|«      | d$   _        d| d$   _        |j'                  d«       |jK                  «       }$|r|$jM                  |«       |$| d&<   y# t,        $ r;}t/        j0                  d|› d|› �«       |‰v r‰j3                  |«       Y d}~�Œïd}~ww xY w# t,        $ r+}t/        j0                  d|› d|› d|› �«       d}Y d}~�Œ/d}~ww xY w# t,        $ r;}t/        j0                  d|› d|› �«       |‰v r‰j3                  |«       Y d}~�Œ'd}~ww xY w# t,        $ rK}t/        j0                  d%|«       d‰v r‰j3                  d«       d‰v r‰j3                  d«       Y d}~�Œ=d}~ww xY w)'aÄ  
        Calculate positions for all requested celestial bodies and special points.

        This comprehensive method calculates positions for a wide range of astrological
        points including traditional planets, lunar nodes, asteroids, trans-Neptunian
        objects, fixed stars, Arabic parts, and specialized points like Vertex.

        The calculation is performed selectively based on the active_points list for
        performance optimization. Some Arabic parts automatically activate their
        prerequisite points if needed.

        Args:
            data (Dict[str, Any]): Main calculation data dictionary. Updated with all
                calculated planetary positions and related metadata.
            active_points (List[AstrologicalPoint]): Mutable list of points to calculate.
                Modified during execution to remove failed calculations and add
                automatically required points for Arabic parts.

        Celestial Bodies Calculated:
            Traditional Planets:
                - Sun, Moon, Mercury, Venus, Mars, Jupiter, Saturn
                - Uranus, Neptune, Pluto

            Lunar Nodes:
                - Mean Node, True Node (North nodes)
                - Mean South Node, True South Node (calculated as opposites)

            Lilith Points:
                - Mean Lilith (Mean Black Moon Lilith)
                - True Lilith (Osculating Black Moon Lilith)

            Asteroids:
                - Ceres, Pallas, Juno, Vesta (main belt asteroids)

            Centaurs:
                - Chiron, Pholus

            Trans-Neptunian Objects:
                - Eris, Sedna, Haumea, Makemake
                - Ixion, Orcus, Quaoar

            Fixed Stars:
                - 23 stars (expanded in v5.12 from 2): Regulus, Spica,
                  Aldebaran, Antares, Sirius, Fomalhaut, Algol, Betelgeuse,
                  Canopus, Procyon, Arcturus, Pollux, Deneb, Altair, Rigel,
                  Achernar, Capella, Vega, Alcyone, Alphecca, Algorab,
                  Deneb Algedi, Alkaid
                - Includes apparent visual magnitude via ``swe.fixstar2_mag``
                - Includes equatorial declination via ``FLG_EQUATORIAL``
                - Includes ecliptic speed (precession drift, ~50 arcsec/yr)

            Arabic Parts (Lots):
                - Pars Fortunae (Part of Fortune)
                - Pars Spiritus (Part of Spirit)
                - Pars Amoris (Part of Love/Eros)
                - Pars Fidei (Part of Faith)

            Special Points:
                - Earth (for heliocentric perspectives)
                - Vertex and Anti-Vertex

        Side Effects:
            - Updates data dictionary with all calculated positions
            - Modifies active_points list by removing failed calculations
            - Adds prerequisite points for Arabic parts calculations
            - Updates data["active_points"] with successfully calculated objects

        Error Handling:
            Individual calculation failures (e.g., asteroids outside ephemeris range)
            are handled gracefully with logging and removal from active_points.
            This prevents cascade failures while maintaining calculation integrity.

        Arabic Parts Logic:
            - Day/night detection uses pre-computed is_diurnal from chart's sect classification
            - Sect is computed from tropical geocentric Sun altitude (independent of chart settings)
            - Automatic activation of required base points (Sun, Moon, Ascendant, etc.)
            - Classical formulae with day/night variations where applicable
            - All parts marked as non-retrograde (conceptual points)

        Performance Notes:
            - Only points in active_points are calculated (selective computation)
            - Failed calculations are removed to prevent repeated attempts
            - Some expensive calculations (like distant TNOs) may timeout
            - Fixed stars use different calculation methods than planets

        Note:
            The method maintains a running list of successfully calculated planets
            and updates the active_points list to reflect actual availability.
            This ensures that dependent calculations and aspects only use valid data.
        r>  r’   c                 ó   •— ‰ xs | ‰v S rx   ry   r@  s    €r~   rA  zGAstrologicalSubjectFactory._calculate_planets.<locals>.should_calculate¾  rB  r€   r   r  rþ   rH  )r;   r=   r   r*   r;   rs   rj  rk  Nr…  r=   rt   zCould not calculate z position: r.   r    z(Could not load fixed-star magnitude for z (z): )rc  rd  r†  Ú	magnitudeFÚVertexÚAnti_Vertexr›   rš   ÚVrC  r£  ÚvertexÚanti_vertexz:Could not calculate Vertex/Anti-Vertex position, error: %srù   )'r   ro  rQ   Úitemsrì   r�  rŠ  r¤   rˆ  r‰  r†  ru  rv  r  r   rd  r   rr  rs  rt  rY   Ú
AST_OFFSETr  rÄ   r	  rŒ  rq   rr   r  Ú
fixstar_utÚlenÚfixstar2_magr‘   r­  Ú	houses_exrÃ   r  Úcopyr¤  )%r0  rù   r  rA  rc  r  r¶   r‚  rƒ  r€  r�  Únode_keyÚnode_eqÚ
south_nodeÚ	north_keyÚ
north_dataÚ	south_degÚsouth_node_trueÚtno_nameÚasteroid_numr  Ú	star_nameÚswe_nameÚpos_eclÚstar_degÚ
star_speedÚpos_eqÚstar_decÚstar_magÚstar_keyr�  Úpart_configr’  rx  Ú
vertex_degÚanti_vertex_degÚall_calculated_pointss%    `                                   r~   r  z-AstrologicalSubjectFactory._calculate_planets\  sâ  ø€ ðD	?Ô$5ð 	?¼$õ 	?ð !4ˆ
Ø˜,Ñ'ˆ
Ø�X‘ˆØÐ 3Ñ4Ðð 79Ðô '7×&<Ñ&<Ó&>ó 7	CÑ"ˆK˜Ù Õ,Ü*×CÑCØØØØØØ$ØØ&Ø!ô
ð Ð"TÑTØ*×0Ñ0Ó2�HØ 4Ñ'ä"%§+¡+¨j¸)ÀUÌS×M_ÑM_ÑE_Ó"`ÐabÑ"c˜Ø5<¸Q±Z˜˜X™Ô2ð Ð"9Ò9Ø4K�JØ +× 1Ñ 1Ó 3�IÙ'¨
Ô3¸	ÀTÑ8IØ%)¨)¡_˜
Ü$(§I¡I¨j×.@Ñ.@À3Ñ.FÈÓ$L˜	Ü3RØ%Ø&Ø'1Ø7A×7GÑ7GÐ7S :×#3Ñ#3Ñ"3ÐY]ØCM×CYÑCYÐCe¨×)?Ñ)?Ñ(?Ðkoô4˜˜Z×-Ñ-Ó/Ñ0ô :JÈ)ÐUeÓ9f˜˜Z×-Ñ-Ó/Ñ0Ô6Ø>H×>SÑ>S˜˜Z×-Ñ-Ó/Ñ0Ô;Ø*×1Ñ1°*Ô=àÐ"9Ô9Ø9P�OØ +× 1Ñ 1Ó 3�IÙ'¨Ö8¸YÈ$Ó=NØ%)¨)¡_˜
Ü$(§I¡I¨j×.@Ñ.@À3Ñ.FÈÓ$L˜	Ü8WØ%Ø+Ø'1Ø7A×7GÑ7GÐ7S :×#3Ñ#3Ñ"3ÐY]ØCM×CYÑCYÐCe¨×)?Ñ)?Ñ(?Ðkoô9˜˜_×2Ñ2Ó4Ñ5ô ?OÈyÐZjÓ>k˜˜_×2Ñ2Ó4Ñ5Ô;ØCM×CXÑCX˜˜_×2Ñ2Ó4Ñ5Ô@Ø*×1Ñ1°/ÖBðo7	Côz '2×&7Ñ&7Ó&9ò 	7Ñ"ˆH�lÙ Õ)ð7Ü.×GÑGØØ ÜŸ™¨Ñ5Ø"ØØ(Ø"Ø*Ø%õ
ð	7ô. %ó #	8ˆIÙ 	Õ*ð!8ä3×7Ñ7¸	À9ÓM�Hä!Ÿn™n¨X°zÀ5ÓIÈ!ÑL�GØ& q™z�HÜ/2°7«|¸aÒ/? ¨¢ÀS�Jä Ÿ^™^¨H°jÀ%Ì#×J\ÑJ\ÑB\Ó]Ð^_Ñ`�FÜ,/°«K¸!ªO˜v ašyÀ�Hð(Ü#&×#3Ñ#3°HÓ#=¸aÑ#@˜ð
  )Ÿ™Ó0�HÜ%DØ Ø!Ø#-Ø(Ø$,Ø"*ô&�D˜‘Nô ,<¸HÐFVÓ+W�D˜‘NÔ(Ø05�D˜‘NÔ-Ø&×-Ñ-¨iÖ8ð?#	8ôT ':×&?Ñ&?Ó&Aò 	Ñ"ˆI�{Ù 	Õ*Ü*×AÑAØØØØØØ$ØØ!Ø&õ
ð	ñ" ˜HÔ%Ñ)9¸-Ô)Hð"8äŸ=™=Ø˜|Ñ,Ø˜U™Ø˜U™ÜŸ™ C›Øô‘��5ð # 1™X�
ñ $ HÔ-Ü%DÀZÐQYÐfpÔ%q�D˜‘NÜ+;¸JÐHXÓ+Y�D˜‘NÔ(Ø05�D˜‘NÔ-Ø&×-Ñ-¨hÔ7ñ $ MÔ2Ü&*§i¡i°
¸SÑ0@À#Ó&F�OÜ*IØ'¨À:ô+�D˜Ñ'ô 1AÀÐRbÓ0c�D˜Ñ'Ô-Ø5:�D˜Ñ'Ô2Ø&×-Ñ-¨mÔ<ð !3× 7Ñ 7Ó 9ÐÙ!Ø!×(Ñ(Ð)?Ô@Ø 5ˆˆ_Òøô[ !ò 7Ü—O‘OÐ&:¸8¸*ÀKÐPQÈsÐ$SÔTØ =Ñ0Ø%×,Ñ,¨XÔ6ÿùð7ûô2 %ò (ÜŸ™Ð*RÐS\ÐR]Ð]_Ð`hÐ_iÐilÐmnÐloÐ(pÔqØ#'žûð(ûô  !ò 8Ü—O‘OÐ&:¸9¸+À[ÐQRÐPSÐ$TÔUØ  MÑ1Ø%×,Ñ,¨YÔ7ÿùð8ûôr ò 8Ü—‘Ð \Ð^_Ô`Ø˜}Ñ,Ø!×(Ñ(¨Ô2Ø  MÑ1Ø!×(Ñ(¨Ô7ÿùð8úsv   Ë.U+ÌB
W)ÎV2Î2AW)ÑC'X0 Õ+	V/Õ40V*Ö*V/Ö2	W&Ö; W!×W)×!W&×&W)×)	X-×20X(Ø(X-Ø0	ZØ9A Y?Ù?Zc                 ó\   — t        j                  | d   «      }|j                  d«      | d<   y)a  
        Calculate the day of the week for the given astronomical event.

        Determines the day of the week corresponding to the local datetime
        using the standard library for consistency.

        Args:
            data (Dict[str, Any]): Calculation data dictionary containing
                iso_formatted_local_datetime. Updated with the calculated day_of_week string.

        Side Effects:
            Updates data dictionary with:
            - day_of_week: Human-readable day name (e.g., "Monday", "Tuesday")
        r3  z%AÚday_of_weekN)r   r$  Ústrftime)r0  r)  s     r~   r  z1AstrologicalSubjectFactory._calculate_day_of_weekŠ  s-   € ô  ×#Ñ# DÐ)GÑ$HÓIˆØ Ÿk™k¨$Ó/ˆˆ]Òr€   rx   )&rÉ   rÊ   rË   rÌ   Úclassmethodr%   r#   r&   Ú(DEFAULT_GEONAMES_CACHE_EXPIRE_AFTER_DAYSrÃ   r   rê   rÎ   ro  r   r   r   r   r   r   r   r   r•   r-  r/  Ústaticmethodr   r	   rÐ   r  r  r   r�  r“  r  r­  r  r  ry   r€   r~   rì   rì     sc  „ ñ>ð@ ð Ø"Ø#Ø!Ø"Ø $Ø"Ø $Ø#Ø#Ø $Ø+/ØØ"5Ø04Ø;[Ø,DØ'OØ!%Ø$(Ø;?Ø&*Ø.2Ø37ð3g5ð6 Ø*/ò9g5àðg5ð �s‰mðg5ð ˜‰}ð	g5ð
 �c‰]ðg5ð �s‰mðg5ð ˜‘ðg5ð �s‰mðg5ð ˜‘ðg5ð �e‰_ðg5ð �e‰_ðg5ð ˜‘ðg5ð $ C™=ðg5ð ðg5ð  ðg5ð    Ñ-ð!g5ð" #9ð#g5ð$ *ð%g5ð& "%ð'g5ð( ˜‘ð)g5ð* ˜5‘/ð+g5ð,   Ð%6Ñ 7Ñ8ð-g5ð.  $ð/g5ð0 % U™Oð1g5ð2 "*¨%¡ð3g5ð6 ð7g5ð8 $(ð9g5ð: 
"ò;g5ó ðg5ðR	 ð
  ØØØØØØ!:Ø"5Ø04Ø;[Ø,DØ$(Ø;?Ø&*Ø*/Ø.2Ø37ñ)[
àð[
ð ð[
ð ð	[
ð
 ð[
ð ð[
ð ð[
ð ð[
ð ð[
ð ð[
ð  ð[
ð   Ñ-ð[
ð #9ð[
ð *ð[
ð ˜5‘/ð[
ð    Ð%6Ñ 7Ñ8ð![
ð"  $ð#[
ð$ $(ð%[
ð& % U™Oð'[
ð( "*¨%¡ð)[
ð* 
"ò+[
ó ð[
ðz ð Ø"Ø $Ø#Ø#Ø $Ø+/ØØ"5Ø04Ø;[Ø,DØ;?Ø&*Ø*/Ø.2Ø37ñ%A
àðA
ð �s‰mðA
ð ˜‘ð	A
ð
 �e‰_ðA
ð �e‰_ðA
ð ˜‘ðA
ð $ C™=ðA
ð ðA
ð  ðA
ð   Ñ-ðA
ð #9ðA
ð *ðA
ð   Ð%6Ñ 7Ñ8ðA
ð  $ðA
ð  $(ð!A
ð" % U™Oð#A
ð$ "*¨%¡ð%A
ð& 
"ò'A
ó ðA
ðF ð4>¨$¨s°C¨x©.ð 4>ÀLð 4>ÐUYò 4>ó ð4>ðl ðP&Ø�3˜�8‰nðP&Ø-5°dÐ;LÑ6MÑ-NðP&à	ÐÑ	 òP&ó ðP&ðd ðM2Ø�3˜�8‰nðM2à&ðM2ð ðM2ð ð	M2ð
 ðM2ð ˜u™+ðM2ð ðM2ð !Ð!2Ñ3ðM2ð Ð-Ñ.ðM2ð 
òM2ó ðM2ð^ ð7<Ø ð7<à�3˜�8‰nð7<ð ð7<ð ð	7<ð
 ˜u™+ð7<ð ð7<ð Ð-Ñ.ð7<ð 
ò7<ó ð7<ðr ð*Øð*àð*ð ð*ð ð	*ð
 
ò*ó ð*ðX ðF-Ø$ðF-à�S˜#�X‘ðF-ð �3˜�8‰nðF-ð ð	F-ð
 ðF-ð ˜u™+ðF-ð ðF-ð Ð-Ñ.ðF-ð !Ð!2Ñ3ðF-ð 
òF-ó ðF-ðP ð EIñk6Ø�3˜�8‰nðk6àÐ-Ñ.ðk6ð !)¨Ð.?Ñ)@Ñ Aðk6ð 
ò	k6ó ðk6ðZ	 ð0 T¨#¨s¨(¡^ð 0¸ò 0ó ñ0r€   rì   Ú__main__)r   )*r(   r)   r+   r-   r/   r1   r3   r5   r7   r9   r;   r=   rs   rt   rE   r?   rA   rC   rG   rM   rN   rO   rP   rR   rS   rT   rU   rV   rW   rX   rZ   r[   r�   rŽ   r�   r�   r±  r²  rv   rg  ri  rm  Únew_active_pointszTest Subject)rð   rù   z----T)Úexclude_noneÚindentzkerykeion_subject_example.jsonÚwzutf-8)Úencodingrx   )TrÌ   r&  Úswissephr¤   rÄ   ru  r   Úosr   Úpathlibr   Útypingr   r   r   r	   r
   Údataclassesr   r   Ú
contextlibr   Úkerykeion.fetch_geonamesr   Úkerykeion.schemasr   r   r   r   r   r   r   r   r   Úkerykeion.utilitiesr   r   r   r   r   r   Ú#kerykeion.settings.config_constantsr   r•   r”   r!   rÍ   r#   r%   r&   r×  rQ   rê   rY   rq   rr   rÃ   ru   r‘   r
  r–   rÎ   r¸   r™   rÐ   rì   rÉ   Úkerykeion.schemas.kr_literalsrÚ  r/  ÚsubjectÚprintr|   Úpars_amorisÚerisrù   Ú
pars_fideirµ  Úmodel_dump_jsonÚjson_stringÚopenr  ÚfÚwritery   r€   r~   ú<module>rô     s  ðòó> Û Û Û Ý Ý Ý ß 6Õ 6ß (Ý %õ 3÷
÷ 
õ 
÷÷ õ Fð *Ð Ø9Ð Ø&5Ð �|Ó 5Ø;>Ð  Ð"8Ó >Ø",Ð �ZÓ ,Ø,AÐ ˜/Ó AØ+-Ð (ð2Ø	ˆ1ð2à
ˆAð2ð ˆqð2ð ˆQð	2ð
 ˆAð2ð ˆqð2ð ˆað2ð ˆað2ð ˆqð2ð ˆQð2ð ˜Rð2ð ˜Rð2ð �2ð2ð �2ð2ð ˆRð2ð  ˆbð!2ð" ˆbð#2ð$ ØØØò+2Ð �$Ð(¨#Ð-Ñ.ó ð6 ØØØØØØñ-€ˆTÐ# SÐ(Ñ)ó ò(€ˆTÐ#Ñ$ó ð> �Nð(Ð �d˜3 ˜8‘nó ð 5Ø4ñ?€�Ð'Ð):Ð:Ñ;ó ò 1Ù>Ù@ñò 1Ù>Ù@ñò 2Ù<ñò
 7ÙFññ@Ð �TÐ+¨T°#°s°(©^Ð;Ñ<ó ð.ð "ð
J ó 
Jð ð  ñFØðFà ðFð 
ðFð 
ð	Fð
 
�%‰òFó ðFðR ÷jð jó ðjðZ ÷s=ð s=ó ðs=÷lV0ñ V0ðr, ˆzÒÝ?ò+2Ð�tÐ-Ñ.ó +ðX )×:Ñ:ÀÐ^oÐ:Óp€GÙ	ˆ'�+‰+ÔÙ	ˆ'×
Ñ
ÔÙ	ˆ'�,‰,ÔÙ	ˆ'×
Ñ
Ô Ù	ˆ'×
Ñ
ÔÙ	ˆ&„MÙ	ˆ'×
Ñ
Ôð ×)Ñ)°tÀAÐ)ÓF€Kñ 
ˆiˆd�i‰i‹kÐ<Ñ<¸cÈGÔ	Tð ÐXYØ	�‰�Ô÷ð ð{ ÷zð ús   É!I=É=J