Ë
    }D™j=T  ã                   óB  — d Z ddlmZ ddlmZ ddlmZmZmZ ddl	m
Z
mZ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mZmZmZmZ dd	lZ G d
„ d«      Zedk(  �rE ej<                  d«      Z ej<                  d«      Z  eee ddddddd	d	d	¬«      Z!e!jE                  d¬«      Z# e$d e%e#«      › �«        e$de#d   jL                  › �«       e!jO                  «       Z( e$d e%e(«      › �«        e$de(d   jR                  › �«       e(d   Z*e*jR                  � e$de*jR                  d   › �«        e+ e,d e%e(«      «      «      D ]X  Z- e$de#e-   jL                  › �«        e%e#e-   j\                  «      dkD  r e$d e#e-   j\                  d   d!   › �«        e$d"«       ŒZ y	y	)#a  
Ephemeris Data Factory Module

This module provides the EphemerisDataFactory class for generating time-series
astrological ephemeris data. It enables the creation of comprehensive astronomical
and astrological datasets across specified date ranges with flexible time intervals
and calculation parameters.

Key Features:
    - Time-series ephemeris data generation
    - Multiple time interval support (days, hours, minutes)
    - Configurable astrological calculation systems
    - Built-in performance safeguards and limits
    - Multiple output formats (dictionaries or model instances)
    - Complete AstrologicalSubject instance generation

The module supports both lightweight data extraction (via get_ephemeris_data)
and full-featured astrological analysis (via get_ephemeris_data_as_astrological_subjects),
making it suitable for various use cases from simple data collection to complex
astrological research and analysis applications.

Classes:
    EphemerisDataFactory: Main factory class for generating ephemeris data

Dependencies:
    - kerykeion.AstrologicalSubjectFactory: For creating astrological subjects
    - kerykeion.utilities: For house and planetary data extraction
    - kerykeion.schemas: For type definitions and model structures
    - datetime: For date/time handling
    - logging: For performance warnings

Example:
    Basic usage for daily ephemeris data:

    >>> from datetime import datetime
    >>> from kerykeion.ephemeris_data_factory import EphemerisDataFactory
    >>>
    >>> start = datetime(2024, 1, 1)
    >>> end = datetime(2024, 1, 31)
    >>> factory = EphemerisDataFactory(start, end)
    >>> data = factory.get_ephemeris_data()
    >>> print(f"Generated {len(data)} data points")

Author: Giacomo Battaglia
Copyright: (C) 2025 Kerykeion Project
License: AGPL-3.0
é    )ÚAstrologicalSubjectFactory)ÚAstrologicalSubjectModel)Úget_houses_listÚ&get_available_astrological_points_listÚnormalize_zodiac_type)Ú DEFAULT_HOUSES_SYSTEM_IDENTIFIERÚDEFAULT_PERSPECTIVE_TYPEÚDEFAULT_ZODIAC_TYPE)ÚEphemerisDictModelÚSiderealModeÚHousesSystemIdentifierÚPerspectiveTypeÚ
ZodiacType)ÚdatetimeÚ	timedelta)ÚAnyÚDictÚLiteralÚUnionÚListNc            %       óè   — e Zd ZdZddddddedeed	d
dddfdededed   de	de
de
dedededeedf   dededee	df   dee	df   dee	df   dee
df   dee
df   f"d„Zd#ded efd!„Zd#ded ee   fd"„Zy)$ÚEphemerisDataFactoryaO  
    A factory class for generating ephemeris data over a specified date range.

    This class calculates astrological ephemeris data (planetary positions and house cusps)
    for a sequence of dates, allowing for detailed astronomical calculations across time periods.
    It supports different time intervals (days, hours, or minutes) and various astrological
    calculation systems.

    The factory creates data points at regular intervals between start and end dates,
    with built-in safeguards to prevent excessive computational loads through configurable
    maximum limits.

    Args:
        start_datetime (datetime): The starting date and time for ephemeris calculations.
        end_datetime (datetime): The ending date and time for ephemeris calculations.
        step_type (Literal["days", "hours", "minutes"], optional): The time interval unit
            for data points. Defaults to "days".
        step (int, optional): The number of units to advance for each data point.
            For example, step=2 with step_type="days" creates data points every 2 days.
            Defaults to 1.
        lat (float, optional): Geographic latitude in decimal degrees for calculations.
            Positive values for North, negative for South. Defaults to 51.4769 (Greenwich).
        lng (float, optional): Geographic longitude in decimal degrees for calculations.
            Positive values for East, negative for West. Defaults to 0.0005 (Greenwich).
        tz_str (str, optional): Timezone identifier (e.g., "Europe/London", "America/New_York").
            Defaults to "Etc/UTC".
        is_dst (bool, optional): Whether daylight saving time is active for the location.
            Only relevant for certain timezone calculations. Defaults to False.
        zodiac_type (ZodiacType, optional): The zodiac system to use (tropical or sidereal).
            Defaults to DEFAULT_ZODIAC_TYPE.
        sidereal_mode (Union[SiderealMode, None], optional): The sidereal calculation mode
            if using sidereal zodiac. Only applies when zodiac_type is sidereal.
            Defaults to None.
        houses_system_identifier (HousesSystemIdentifier, optional): The house system
            for astrological house calculations (e.g., Placidus, Koch, Equal).
            Defaults to DEFAULT_HOUSES_SYSTEM_IDENTIFIER.
        perspective_type (PerspectiveType, optional): The calculation perspective
            (geocentric, heliocentric, etc.). Defaults to DEFAULT_PERSPECTIVE_TYPE.
        max_days (Union[int, None], optional): Maximum number of daily data points allowed.
            Set to None to disable this safety check. Defaults to 730 (2 years).
        max_hours (Union[int, None], optional): Maximum number of hourly data points allowed.
            Set to None to disable this safety check. Defaults to 8760 (1 year).
        max_minutes (Union[int, None], optional): Maximum number of minute-interval data points.
            Set to None to disable this safety check. Defaults to 525600 (1 year).
        custom_ayanamsa_t0 (Union[float, None], optional): The reference epoch (as a Julian day)
            for a custom ayanamsa definition. Only used when sidereal_mode is "USER".
            Defaults to None.
        custom_ayanamsa_ayan_t0 (Union[float, None], optional): The ayanamsa value (in degrees)
            at the reference epoch t0. Only used when sidereal_mode is "USER".
            Defaults to None.

    Raises:
        ValueError: If step_type is not one of "days", "hours", or "minutes".
        ValueError: If the calculated number of data points exceeds the respective maximum limit.
        ValueError: If no valid dates are generated from the input parameters.

    Examples:
        Create daily ephemeris data for a month:

        >>> from datetime import datetime
        >>> start = datetime(2024, 1, 1)
        >>> end = datetime(2024, 1, 31)
        >>> factory = EphemerisDataFactory(start, end)
        >>> data = factory.get_ephemeris_data()

        Create hourly data for a specific location:

        >>> factory = EphemerisDataFactory(
        ...     start, end,
        ...     step_type="hours",
        ...     lat=40.7128,  # New York
        ...     lng=-74.0060,
        ...     tz_str="America/New_York"
        ... )
        >>> subjects = factory.get_ephemeris_data_as_astrological_subjects()

    Note:
        Large date ranges with small step intervals can generate thousands of data points,
        which may require significant computation time and memory. The factory includes
        warnings for calculations exceeding 1000 data points and enforces maximum limits
        to prevent system overload.
    Údaysé   g0»'½I@gü©ñÒMb@?zEtc/UTCFNiÚ  i8"  i  Ústart_datetimeÚend_datetimeÚ	step_type)r   ÚhoursÚminutesÚstepÚlatÚlngÚtz_strÚis_dstÚzodiac_typeÚsidereal_modeÚhouses_system_identifierÚperspective_typeÚmax_daysÚ	max_hoursÚmax_minutesÚcustom_ayanamsa_t0Úcustom_ayanamsa_ayan_t0c                 ó*  — || _         || _        || _        || _        || _        || _        || _        || _        t        |	«      | _	        |
| _
        || _        || _        || _        || _        || _        || _        || _        g | _        | j                  dk(  r¾t'        | j                  | j                   z
  j(                  | j                  z  dz   «      D �cg c](  }| j                   t+        || j                  z  ¬«      z   ‘Œ* c}| _        |�rt-        | j$                  «      |kD  �rt/        dt-        | j$                  «      › d| j                  › d�«      ‚| j                  dk(  rÐ| j                  | j                   z
  j1                  «       dz  }t'        t3        |«      | j                  z  dz   «      D �cg c](  }| j                   t+        || j                  z  ¬	«      z   ‘Œ* c}| _        |�r=t-        | j$                  «      |kD  �r$t/        d
t-        | j$                  «      › d| j                   › d�«      ‚| j                  dk(  rÎ| j                  | j                   z
  j1                  «       dz  }t'        t3        |«      | j                  z  dz   «      D �cg c](  }| j                   t+        || j                  z  ¬«      z   ‘Œ* c}| _        |r_t-        | j$                  «      |kD  rGt/        dt-        | j$                  «      › d| j"                  › d�«      ‚t/        d| j                  › �«      ‚| j$                  st/        d«      ‚t-        | j$                  «      dkD  r-t5        j6                  dt-        | j$                  «      › d�«       y y c c}w c c}w c c}w )Nr   r   )r   zToo many days: z > zQ. To prevent this error, set max_days to a higher value or reduce the date range.r   i  )r   zToo many hours: zR. To prevent this error, set max_hours to a higher value or reduce the date range.r   é<   )r   zToo many minutes: zT. To prevent this error, set max_minutes to a higher value or reduce the date range.zInvalid step type: z5No dates found. Check the date range and step values.iè  zLarge number of dates: z#. The calculation may take a while.)r   r   r   r    r!   r"   r#   r$   r   r%   r&   r'   r(   r,   r-   r)   r*   r+   Ú
dates_listÚranger   r   ÚlenÚ
ValueErrorÚtotal_secondsÚintÚloggingÚwarning)Úselfr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   ÚiÚ
hours_diffÚminutes_diffs                        úl/var/www/html/Astrologybackend/backend/venv/lib/python3.12/site-packages/kerykeion/ephemeris_data_factory.pyÚ__init__zEphemerisDataFactory.__init__�   sS  € ð( -ˆÔØ(ˆÔØ"ˆŒØˆŒ	ØˆŒØˆŒØˆŒØˆŒÜ0°Ó=ˆÔØ*ˆÔØ(@ˆÔ%Ø 0ˆÔØ"4ˆÔØ'>ˆÔ$Ø ˆŒØ"ˆŒØ&ˆÔàˆŒØ�>‰>˜VÒ#ô  × 1Ñ 1°D×4GÑ4GÑ G×MÑMÐQU×QZÑQZÑZÐ]^Ñ^Ó_öàð ×#Ñ#¤i°Q¸¿¹±]Ô&CÓCòˆDŒOò œS §¡Ó1°HÓ<Ü Ø%¤c¨$¯/©/Ó&:Ð%;¸3¸t¿}¹}¸oð  N_ð  `óð ð �^‰^˜wÒ&Ø×+Ñ+¨d×.AÑ.AÑA×PÑPÓRÐUYÑYˆJäNSÔTWÐXbÓTcÐgk×gpÑgpÑTpÐstÑTtÓNuöØIJ�×#Ñ#¤i°a¸$¿)¹)±mÔ&DÓDòˆDŒOò œc $§/¡/Ó2°YÓ>Ü Ø&¤s¨4¯?©?Ó';Ð&<¸CÀÇÁÐ?Oð  Pbð  cóð ð �^‰^˜yÒ(Ø ×-Ñ-°×0CÑ0CÑC×RÑRÓTÐWYÑYˆLô œs <Ó0°D·I±IÑ=ÀÑAÓBöàð ×#Ñ#¤i¸¸D¿I¹I¹Ô&FÓFòˆDŒOñ ¤ D§O¡OÓ 4°{Ò BÜ Ø(¬¨T¯_©_Ó)=Ð(>¸cÀ$×BRÑBRÐASð  Thð  ióð ô
 Ð2°4·>±>Ð2BÐCÓDÐDà�ŠÜÐTÓUÐUäˆt�‰Ó $Ò&Ü�O‰OÐ5´c¸$¿/¹/Ó6JÐ5KÐKnÐoÕpð 'ùòIùòùòs   Ã-NÆ4-NÊ-NÚas_modelÚreturnc           	      ó¸  — g }| j                   D �]  }t        j                  di d|j                  “d|j                  “d|j
                  “d|j                  “d|j                  “d| j                  “d| j                  “d| j                  “d	d
“dd
“dd“d| j                  “d| j                  “d| j                  “d| j                  “d| j                  “d| j                   “d| j"                  “Ž}t%        |«      }t'        |«      }|j)                  |j+                  «       ||dœ«       �Œ |r%|D �cg c]  }t-        |d   |d   |d   ¬«      ‘Œ c}S |S c c}w )a  
        Generate ephemeris data for the specified date range.

        This method creates a comprehensive dataset containing planetary positions and
        astrological house cusps for each date in the configured time series. The data
        is structured for easy consumption by astrological applications and analysis tools.

        The returned data includes all available astrological points (planets, asteroids,
        lunar nodes, etc.) as configured by the perspective type, along with complete
        house cusp information for each calculated moment.

        Args:
            as_model (bool, optional): If True, returns data as validated model instances
                (EphemerisDictModel objects) which provide type safety and validation.
                If False, returns raw dictionary data for maximum flexibility.
                Defaults to False.

        Returns:
            list: A list of ephemeris data points, where each element represents one
                calculated moment in time. The structure depends on the as_model parameter:

                If as_model=False (default):
                    List of dictionaries with keys:
                    - "date" (str): ISO format datetime string (e.g., "2020-01-01T00:00:00")
                    - "planets" (list): List of dictionaries, each containing planetary data
                      with keys like 'name', 'abs_pos', 'lon', 'lat', 'dist', 'speed', etc.
                    - "houses" (list): List of dictionaries containing house cusp data
                      with keys like 'name', 'abs_pos', 'lon', etc.

                If as_model=True:
                    List of EphemerisDictModel instances providing the same data
                    with type validation and structured access.

        Examples:
            Basic usage with dictionary output:

            >>> factory = EphemerisDataFactory(start_date, end_date)
            >>> data = factory.get_ephemeris_data()
            >>> print(f"Sun position: {data[0]['planets'][0]['abs_pos']}")
            >>> print(f"First house cusp: {data[0]['houses'][0]['abs_pos']}")

            Using model instances for type safety:

            >>> data_models = factory.get_ephemeris_data(as_model=True)
            >>> first_point = data_models[0]
            >>> print(f"Date: {first_point.date}")
            >>> print(f"Number of planets: {len(first_point.planets)}")

        Note:
            - The calculation time is proportional to the number of data points
            - For large datasets (>1000 points), consider using the method in batches
            - Planet order and availability depend on the configured perspective type
            - House system affects the house cusp calculations
            - All positions are in the configured zodiac system (tropical/sidereal)
        ÚyearÚmonthÚdayÚhourÚminuter"   r!   r#   ÚcityÚPlaceholderÚnationÚonlineFr%   r&   r'   r(   r$   r,   r-   )ÚdateÚplanetsÚhousesrJ   rK   rL   © )r0   r   Úfrom_birth_datarA   rB   rC   rD   rE   r"   r!   r#   r%   r&   r'   r(   r$   r,   r-   r   r   ÚappendÚ	isoformatr   )r8   r>   Úephemeris_data_listrJ   ÚsubjectÚhouses_listÚavailable_planetsÚdatas           r<   Úget_ephemeris_dataz'EphemerisDataFactory.get_ephemeris_dataì   s¤  € ðp 57ÐØ—O‘Oó 	xˆDÜ0×@Ñ@ò Ø—Y’Yðà—j’jðð —H’Hðð —Y’Yð	ð
 —{’{ðð —H’Hðð —H’Hðð —{’{ðñ #ðñ %ðñ ðð !×,Ò,ðð #×0Ò0ðð *.×)FÒ)Fðð "&×!6Ò!6ðð  —{’{ð!ð" $(×#:Ò#:ð#ð$ )-×(DÒ(Dð%ˆGô* *¨'Ó2ˆKÜ FÀwÓ OÐà×&Ñ&°·±Ó0@ÐM^ÐjuÑ'vÖwð3	xñ6 ð 0öàô #¨¨V©¸dÀ9¹oÐVZÐ[cÑVdÖeòð ð
 #Ð"ùòs   Ä4Ec                 ó  — g }| j                   D ]ò  }t        j                  di d|j                  “d|j                  “d|j
                  “d|j                  “d|j                  “d| j                  “d| j                  “d| j                  “d	d
“dd
“dd“d| j                  “d| j                  “d| j                  “d| j                  “d| j                  “d| j                   “d| j"                  “Ž}|j%                  |«       Œô |S )aº  
        Generate ephemeris data as complete AstrologicalSubject instances.

        This method creates fully-featured AstrologicalSubject objects for each date in the
        configured time series, providing access to all astrological calculation methods
        and properties. Unlike the dictionary-based approach of get_ephemeris_data(),
        this method returns objects with the complete Kerykeion API available.

        Each AstrologicalSubject instance represents a complete astrological chart for
        the specified moment, location, and calculation settings. This allows direct
        access to methods like get_sun(), get_all_points(), draw_chart(), calculate
        aspects, and all other astrological analysis features.

        Args:
            as_model (bool, optional): If True, returns AstrologicalSubjectModel instances
                (Pydantic model versions) which provide serialization and validation features.
                If False, returns raw AstrologicalSubject instances with full method access.
                Defaults to False.

        Returns:
            List[AstrologicalSubjectModel]: A list of AstrologicalSubject or
                AstrologicalSubjectModel instances (depending on as_model parameter).
                Each element represents one calculated moment in time with full
                astrological chart data and methods available.

                Each subject contains:
                - All planetary and astrological point positions
                - Complete house system calculations
                - Chart drawing capabilities
                - Aspect calculation methods
                - Access to all Kerykeion astrological features

        Examples:
            Basic usage for accessing individual chart features:

            >>> factory = EphemerisDataFactory(start_date, end_date)
            >>> subjects = factory.get_ephemeris_data_as_astrological_subjects()
            >>>
            >>> # Access specific planetary data
            >>> sun_data = subjects[0].get_sun()
            >>> moon_data = subjects[0].get_moon()
            >>>
            >>> # Get all astrological points
            >>> all_points = subjects[0].get_all_points()
            >>>
            >>> # Generate chart visualization
            >>> chart_svg = subjects[0].draw_chart()

            Using model instances for serialization:

            >>> subjects_models = factory.get_ephemeris_data_as_astrological_subjects(as_model=True)
            >>> # Model instances can be easily serialized to JSON
            >>> json_data = subjects_models[0].model_dump_json()

            Batch processing for analysis:

            >>> subjects = factory.get_ephemeris_data_as_astrological_subjects()
            >>> sun_positions = [subj.sun['abs_pos'] for subj in subjects if subj.sun]
            >>> # Analyze sun position changes over time

        Use Cases:
            - Time-series astrological analysis
            - Planetary motion tracking
            - Aspect pattern analysis over time
            - Chart animation data generation
            - Astrological research and statistics
            - Progressive chart calculations

        Performance Notes:
            - More computationally intensive than get_ephemeris_data()
            - Each subject performs full astrological calculations
            - Memory usage scales with the number of data points
            - Consider processing in batches for very large date ranges
            - Ideal for comprehensive analysis requiring full chart features

        See Also:
            get_ephemeris_data(): For lightweight dictionary-based ephemeris data
            AstrologicalSubject: For details on available methods and properties
        rA   rB   rC   rD   rE   r"   r!   r#   rF   rG   rH   rI   Fr%   r&   r'   r(   r$   r,   r-   rM   )r0   r   rN   rA   rB   rC   rD   rE   r"   r!   r#   r%   r&   r'   r(   r$   r,   r-   rO   )r8   r>   Úsubjects_listrJ   rR   s        r<   Ú+get_ephemeris_data_as_astrological_subjectsz@EphemerisDataFactory.get_ephemeris_data_as_astrological_subjectsI  s=  € ð` ˆØ—O‘Oò 	*ˆDÜ0×@Ñ@ò Ø—Y’Yðà—j’jðð —H’Hðð —Y’Yð	ð
 —{’{ðð —H’Hðð —H’Hðð —{’{ðñ #ðñ %ðñ ðð !×,Ò,ðð #×0Ò0ðð *.×)FÒ)Fðð "&×!6Ò!6ðð  —{’{ð!ð" $(×#:Ò#:ð#ð$ )-×(DÒ(Dð%ˆGð* × Ñ  Õ)ð-	*ð0 Ðó    )F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   r   r	   r   r   r5   ÚfloatÚstrÚboolr   r   r   r   r   r=   ÚlistrV   r   r   rY   rM   rZ   r<   r   r   I   s|  „ ñQðn :@ØØØØØØ"5Ø37Ø;[Ø,DØ%(Ø&*Ø(.Ø15Ø6:ñ%Mqà ðMqð ðMqð Ð5Ñ6ð	Mqð
 ðMqð ðMqð ðMqð ðMqð ðMqð  ðMqð ˜\¨4Ð/Ñ0ðMqð #9ðMqð *ðMqð ˜˜T˜	Ñ"ðMqð ˜˜d˜Ñ#ðMqð  ˜3 ˜9Ñ%ð!Mqð" " %¨ +Ñ.ð#Mqð$ "' u¨d {Ñ!3ó%Mqñ^[#¨4ð [#¸Dó [#ñziÀDð iÐUYÐZrÑUsô irZ   r   Ú__main__z
2020-01-01z
2020-01-03r   r/   gçŒ(íýB@g
×£p=º7@zEurope/AthensF)r   r   r   r    r!   r"   r#   r$   r*   r+   r)   T)r>   z!Number of ephemeris data points: zFirst data point date: z!Number of astrological subjects: zFirst subject sun position: z
Sun sign: Úsigné   zDate: zSun position from dict: Úabs_posz---)/r^   Ú	kerykeionr   Úkerykeion.schemas.kr_modelsr   Úkerykeion.utilitiesr   r   r   Ú&kerykeion.astrological_subject_factoryr   r	   r
   Úkerykeion.schemasr   r   r   r   r   r   r   Útypingr   r   r   r   r   r6   r   r[   ÚfromisoformatÚ
start_dateÚend_dateÚfactoryrV   Úephemeris_dataÚprintr2   rJ   rY   ÚsubjectsÚsunÚfirst_subjectr1   Úminr9   rK   rM   rZ   r<   ú<module>rw      sâ  ðñ.õ` 1Ý @÷ñ ÷
ñ ÷
õ ÷ )ß 2Õ 2Û ÷iñ iðX ˆzÓØ'�×'Ñ'¨Ó5€JØ%ˆx×%Ñ% lÓ3€Há"Ø!ØØØØØØØØØØô€Gð ×/Ñ/¸Ð/Ó>€NÙ	Ð-©c°.Ó.AÐ-BÐ
CÔDÙ	Ð# N°1Ñ$5×$:Ñ$:Ð#;Ð
<Ô=ð ×BÑBÓD€HÙ	Ð-©c°(«m¨_Ð
=Ô>Ù	Ð(¨°!©¯©Ð(9Ð
:Ô;ð ˜Q‘K€MØ×ÑÐ$Ù�
˜=×,Ñ,¨VÑ4Ð5Ð6Ô7ñ ‘3�q™#˜h›-Ó(Ó)ò ˆÙ��~ aÑ(×-Ñ-Ð.Ð/Ô0Ùˆ~˜aÑ ×(Ñ(Ó)¨AÒ-ÙÐ,¨^¸AÑ->×-FÑ-FÀqÑ-IÈ)Ñ-TÐ,UÐVÔWÙˆe�ñ	ðE rZ   