
    c
i^                     b   d Z ddlZddlZddlmZmZ ddlmZ ej        	                    d e
 ee          j        j                             ddlmZ ddlmZ ddlmZ  eed	          Zd
ZdefdZefde
dedee
         fdZdefdZedk    r ej         e                       dS dS )a!  
Weekly health report script.

Generates a Slack-formatted summary of the previous week's health data
and posts it to the configured Slack channel.

Usage:
    python scripts/weekly_report.py

Cron example (every Monday at 11:00 AM):
    0 11 * * 1 cd /root/projects/butler && /root/projects/butler/venv/bin/python /root/projects/butler/scripts/weekly_report.py >> /root/projects/butler/logs/cron.log 2>&1

Required env vars:
    SLACK_BOT_TOKEN      - Slack bot OAuth token (xoxb-...)
    SLACK_REPORT_CHANNEL - Target channel ID (C0XXXXXXXXX)
    N)date	timedelta)Path)WeeklyReportGenerator)load_env_with_extras)setup_loggerzweekly_report.log)log_filei<  returnc                      t          j                    } |                                 }| t          |          z
  }|t          d          z
  S )zReturn the Monday of the previous week.

    Always returns the most recently completed Monday (never today),
    so the full 7-day week is available.

    Returns:
        Date of last Monday.
    )days   )r   todayweekdayr   )r   days_since_mondaythis_mondays      scripts/weekly_report.py_last_mondayr   $   sI     JLLE)):;;;;K*****    textmax_lenc                    t          |           |k    r| gS g }g }d}|                     d          D ]m}|t          |          z   |k    r.|r,|                    d                    |                     g }d}|                    |           |t          |          z  }n|r(|                    d                    |                     |S )zSplit a long message into chunks that fit within Slack's limits.

    Splits on newline boundaries when possible.

    Args:
        text: Full message text.
        max_len: Maximum characters per chunk.

    Returns:
        List of message chunks.
    r   T)keepends )len
splitlinesappendjoin)r   r   chunkscurrent_linescurrent_lenlines         r   _split_messager"   5   s     4yyGvF!MK.. ! !T"W,,,MM"''-00111MKT"""s4yy  .bggm,,---Mr   c            	         ddl m }  |                                 }t                              d           t                              d|                                            t                              d           t                       t          j                            d          }t          j                            d          }|st          	                    d           dS |st          	                    d	           dS t                      }t                              d
|            	 t                                          |          }n5# t          $ r(}t                              d|            Y d}~dS d}~ww xY wt                              dt          |           d           	 ddlm}  ||          }t%          |          }	t                              dt          |	           d|            t'          |	          D ]M\  }
}|                    ||           t                              d|
dz    dt          |	           d           Nn5# t          $ r(}t                              d|            Y d}~dS d}~ww xY w|                                 }||z
                                  }t                              d|dd           t                              d           dS )zoGenerate and post the weekly health report.

    Returns:
        Exit code: 0 for success, 1 for failure.
    r   )datetimez<============================================================zWeekly Report Started: SLACK_BOT_TOKENSLACK_REPORT_CHANNELz)SLACK_BOT_TOKEN is not set in environment   z.SLACK_REPORT_CHANNEL is not set in environmentz$Generating report for week starting zReport generation failed: NzReport generated (z chars))	WebClient)tokenzSending z message chunk(s) to )channelr   zChunk /z sentzFailed to send Slack message: z"Weekly report complete. Duration: z.2fs)r$   nowloggerinfo	isoformatr   osenvirongeterrorr   r   generate	Exception	exceptionr   	slack_sdkr(   r"   	enumeratechat_postMessagetotal_seconds)r$   
start_timeslack_tokenreport_channel
week_startreport_texter(   clientr   ichunkend_timedurations                 r   mainrG   V   s
    "!!!!!J
KK
KKB**>*>*@*@BBCCC
KK*..!233KZ^^$:;;N @AAAq EFFFqJ
KKCzCCDDD+--66zBB   9a99:::qqqqq KK>S%5%5>>>???''''''---,,Qs6{{QQQQRRR!&)) 	= 	=HAu##N#GGGKK;Q;;V;;;<<<<	=    =!==>>>qqqqq ||~~H:%4466H
KKDXDDDDEEE
KK1s1   2!E 
FFF5B+I! !
J+JJ__main__)__doc__r1   sysr$   r   r   pathlibr   pathinsertstr__file__parenthealth.analytics.weekly_reportr   health.utils.env_loaderr   health.utils.logging_configr   __name__r.   _MAX_SLACK_MESSAGE_LENr   intlistr"   rG   exit r   r   <module>rZ      sq   " 
			 



 $ $ $ $ $ $ $ $       33ttH~~,344 5 5 5 @ @ @ @ @ @ 8 8 8 8 8 8 4 4 4 4 4 4	h)<	=	=	= +d + + + +" .D   s S	    B8c 8 8 8 8v zCHTTVV r   