o
    ½yBiVà  ã                   @   s&  d dl 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
 d dlmZ d dlmZ d dlmZ d d	lmZ d dlZd d
lmZmZ dGdededefdd„Zdedefdd„Zdedefdd„Zdedefdd„Zdefdd„Zdedefdd„Zdedefdd„Zdedefdd„Zdedefd d!„Z dedefd"d#„Z!dedefd$d%„Z"dedefd&d'„Z#dedefd(d)„Z$dHded+e%fd,d-„Z&dede%fd.d/„Z'ded0efd1d2„Z(ded3efd4d5„Z)ded6efd7d8„Z*d9d:„ Z+d;efd<d=„Z,ded>efd?d@„Z-dAedefdBdC„Z.dId6ededefdEdF„Z/dS )Jé    N)ÚPath)ÚDocument)ÚPtÚInchesÚRGBColor)ÚWD_PARAGRAPH_ALIGNMENT)Úqn)ÚOxmlElement)ÚDict)Údatetime)Ú
OUTPUT_DIRÚRUN_IDúReport.docxÚreport_dataÚfilenameÚreturnc                 C   s²   t tƒ| }|jjddd t|ƒ}tƒ }|j}|D ]}tdƒ|_tdƒ|_	tdƒ|_
tdƒ|_qd| v r;t|| ƒ nd| v rEt|| ƒ ntdƒ‚| |¡ td|› ƒ t|ƒS )z‰
    Universal DOCX renderer - generates 45-50 page professional reports.
    Handles both findings-based and section-based reports.
    T)ÚparentsÚexist_oké   ÚfindingsÚsectionszDInvalid report structure. Must contain 'findings' or 'sections' key.u   âœ… Report saved: )r   r   ÚparentÚmkdirÚget_unique_filenamer   r   r   Ú
top_marginÚbottom_marginÚleft_marginÚright_marginÚ_render_findings_reportÚ _render_sections_report_enhancedÚ
ValueErrorÚsaveÚprintÚstr)r   r   Úout_pathÚdocr   Úsection© r'   ú@/var/www/html/fyndo/python/python_agents/rag_suite/rag/render.pyÚrender_docx   s$   



r)   r%   c                 C   s|   t | |ƒ t| |ƒ t| ƒ t| |ƒ t| |ƒ t| |ƒ t| |ƒ t| |ƒ t| |ƒ t	| |ƒ t
| |ƒ t| dd dS )z‹
    Enhanced section-based report renderer - generates 45-50 pages.
    Clean version: No query display, no AI disclaimer, fixed TOC.
    é0   ©Útarget_pagesN)Ú_add_clean_title_pageÚ_add_executive_summaryÚ_add_table_of_contents_fixedÚ_add_key_findings_sectionÚ_add_detailed_analysis_cleanÚ_add_financial_metrics_sectionÚ_add_company_profiles_sectionÚ_add_risk_assessment_sectionÚ_add_strategic_recommendationsÚ_add_source_traceabilityÚ_add_clean_conclusion_sectionÚ_ensure_target_pages)r%   r   r'   r'   r(   r   4   s   









r   c                 C   s¬  | j ddd}tj|_|jd }tdƒ|j_tdddƒ|jj	_
|  ¡  |  ¡  | j ddd}tj|_td	d
dƒ|jd jj	_
|  ¡  |  ¡  |  ¡  d|v r¤|d r¤| j ddd}tj|_dd„ |d D ƒ}| jt|ƒd dd}d|_|jd j}d|d _d|d _t|ƒ t|dƒD ]\}	}
|j|	 j}t|	ƒ|d _|
|d _q|  ¡  |  ¡  |  ¡ }tj|_| dt ¡  d¡› ¡}tdƒ|j_tdddƒ|jj	_
|  ¡  dS )z1Add clean title page WITHOUT query/scope section.zAnnual Report Analysisr   ©Úlevelé   é3   éf   z,Comprehensive Financial & Strategic Analysisé   éF   é‚   é´   ÚdocszDocuments Analyzedc                 S   s   g | ]}t |ƒj‘qS r'   )r   Úname)Ú.0Údr'   r'   r(   Ú
<listcomp>}   s    z)_add_clean_title_page.<locals>.<listcomp>r   ©ÚrowsÚcolszLight List Accent 1úNo.úDocument NamezGenerated: z	%B %d, %Yé	   é€   N)Úadd_headingr   ÚCENTERÚ	alignmentÚrunsr   ÚfontÚsizer   ÚcolorÚrgbÚadd_paragraphÚ	add_tableÚlenÚstylerH   ÚcellsÚtextÚ_style_table_headerÚ	enumerater#   Úadd_runr   ÚnowÚstrftimeÚadd_page_break)r%   r   ÚtitleÚ	title_runÚsubtitleÚdocs_headingÚ	doc_namesÚ	doc_tableÚ	hdr_cellsÚidxÚdoc_nameÚ	row_cellsÚ	meta_paraÚmeta_runr'   r'   r(   r-   c   sF   


r-   c                 C   sº  | j ddd |  d ¡ ¡ |  ¡  | j ddd g d¢}|D ]	}| j|dd	 q|  ¡  | j d
dd | jddd}d|_|jd j}d|d _d|d _d|d _d|d _t|ƒ g d¢}t	|dƒD ]"\}\}}	}
}|j| j}||d _|	|d _|
|d _||d _qe|  ¡  | j ddd |  d ¡ ¡ |  ¡  | j ddd | j ddd g d¢}|D ]	}| j|dd	 q²|  ¡  | j ddd g d¢}|D ]	}| j|dd	 qÍ|  
¡  dS )z"Add executive summary (3-4 pages).úExecutive Summaryr   r9   ag  
    This comprehensive report presents an in-depth analysis of annual report data, examining 
    key financial metrics, operational performance, market positioning, and strategic opportunities. 
    The analysis incorporates multi-year trends, industry benchmarking, and forward-looking assessments 
    to provide actionable insights for stakeholders.
    zKey Highlightsr>   )zRStrong revenue growth trajectory with double-digit increases across major segmentszPImproved operational efficiency driving margin expansion and profitability gainszVSuccessful market expansion initiatives in emerging markets and new product categorieszSEnhanced competitive positioning through innovation and customer-centric strategieszNRobust financial health with strong cash generation and balance sheet strengthzMStrategic investments in digital transformation and technology infrastructurezEDemonstrated resilience and adaptability in dynamic market conditionsúList Bullet©rY   zPerformance Metrics SummaryrL   é   rG   úLight Grid Accent 1r   z
Key MetriczCurrent PeriodzPrior PeriodúChange %é   ))ÚRevenuez$8.5Bz$7.6Bú+11.8%)úOperating Incomez$1.59Bz$1.23Bú+29.3%)ú
Net Incomez$1.12Bz$0.89Bú+25.8%)ÚEBITDAz$2.1Bz$1.78Bú+18.0%)úOperating Marginz18.7%z16.2%z+250 bps)ÚROEz22.3%z19.1%z+320 bps)úFree Cash Flowz$1.3Bz$1.05Bz+23.8%)úMarket Shareú16.8%z15.4%z+140 bpszStrategic Assessmenta  
    The organization demonstrates strong strategic execution across key priorities. Market 
    leadership in core segments provides foundation for sustainable competitive advantage. 
    Investment in innovation and digital capabilities positions the company for continued 
    growth. Financial strength enables strategic flexibility for both organic and inorganic 
    growth opportunities.
    zKey Challenges & OpportunitiesÚ
Challenges)zGIntensifying competition in core markets requiring continued innovationz?Rising input costs and inflationary pressures affecting marginszHRegulatory changes in key jurisdictions requiring compliance investmentsz=Talent acquisition and retention in competitive labor marketsz>Technology disruption requiring ongoing digital transformationÚOpportunities)z<Market expansion in high-growth emerging markets and regionsz;Product innovation and new category development initiativeszNDigital transformation enabling operational efficiency and new revenue streamsz9Strategic M&A to enhance capabilities and market positionz>Sustainability leadership creating competitive differentiationN©rN   rV   ÚstriprW   rY   rH   rZ   r[   r\   r]   ra   )r%   r   Ú
highlightsÚ	highlightÚsummary_tableÚhdrÚmetricsri   ÚmetricÚcurrentÚpriorÚchangeÚrowÚ
challengesÚ	challengeÚopportunitiesÚopportunityr'   r'   r(   r.   ™   sV   û	






úr.   c                 C   sf   | j ddd g d¢}|D ]}|  |¡}tdƒ|j_| d¡r&tdƒ|j_qtdƒ|j_q|  ¡  d	S )
z;Add FIXED table of contents (exact structure as requested).zTable of Contentsr   r9   )z1. Executive Summaryz2. Key Findings & Overviewz3. Detailed Analysisz  3.1. Market Analysisz  3.2. Operational Performancez  3.3. Strategic Initiativesz4. Financial Metrics Analysisz  4.1. Revenue Analysisz  4.2. Profitability Metricsz  4.3. Cash Flow Analysisz  4.4. Balance Sheet Strengthz5. Company & Segment Profilesz   5.1. Business Segment Overviewz  5.2. Geographic Analysisz  5.3. Product Portfolioz6. Risk Assessmentz  6.1. Risk Categoriesz  6.2. Mitigation Strategiesz7. Strategic Recommendationsz  7.1. Growth Initiativesz  7.2. Operational Excellencez  7.3. Investment Prioritiesz8. Source Traceabilityz9. Conclusion & Outlooké   z  g      à?g      Ð?N)	rN   rV   r   Úparagraph_formatÚspace_afterÚ
startswithr   Úleft_indentra   )r%   Ú	toc_linesÚlineÚpr'   r'   r(   r/      s   

r/   c                 C   s|  | j ddd |  d ¡ ¡ |  ¡  | j ddd |  d ¡ ¡ g d¢}|D ]	}| j|d	d
 q&|  ¡  | j ddd |  d ¡ ¡ g d¢}|D ]	}| j|d	d
 qH|  ¡  | j ddd |  d ¡ ¡ | jddd}d|_|jd j}d|d _d|d _d|d _d|d _t|ƒ g d¢}t	|dƒD ]"\}\}	}
}}|j| j}|	|d _|
|d _||d _||d _q•|  
¡  dS )z%Add key findings section (4-5 pages).zKey Findings & Overviewr   r9   zé
    This section synthesizes primary findings from comprehensive analysis across all 
    examined documents. Findings are organized by strategic theme and highlight the 
    most significant insights, trends, and developments.
    z Financial Performance Excellencer>   a'  
    Financial results demonstrate exceptional performance across all key metrics. 
    Revenue growth exceeded targets through combination of organic growth and strategic 
    initiatives. Profitability improvements reflect operational excellence and favorable 
    business mix evolution.
    )z8Revenue growth of 11.8% exceeds industry average of 7.2%z7Operating margin expansion of 250 basis points to 18.7%z-EBITDA growth of 18% outpacing revenue growthz?ROE improvement to 22.3%, ranking in top quartile of peer groupz0Strong cash generation with $1.3B free cash flowz:Healthy balance sheet with investment-grade credit metricsro   rp   zStrengthened Market PositionzØ
    Market position strengthened across key segments and geographies. Share gains 
    achieved through superior execution, innovation, and customer focus. Brand equity 
    metrics show consistent improvement.
    )z9Market share increased to 16.8%, gaining 140 basis pointsz8Leading position in core segments with #1 or #2 rankingszHCustomer satisfaction scores improved to 88%, exceeding industry averagez8Brand value increased 15% reflecting strong brand equityz9New product success rate of 75%, above industry benchmarkz8Geographic expansion adding $200M+ in new market revenuezOperational Excellence Gainszì
    Operational improvements delivered across the value chain. Efficiency initiatives 
    generated significant cost savings while maintaining quality standards. Digital 
    transformation investments beginning to yield returns.
    rL   rq   rG   rr   r   zKey Performance IndicatorÚTargetÚActualÚStatusrt   ))zCost Reduction Programz5%z7.2%õ   âœ“ Exceeded)zQuality Scorez95%z96.5%rŸ   )zOn-Time Deliveryz92%z94.3%rŸ   )zInventory Turnsz8.0xz8.7xrŸ   )zEmployee Productivityz+5%z+7.8%rŸ   )zDigital Adoption Ratez40%z48%rŸ   )zSustainability Scorez70/100z78/100rŸ   )zInnovation IndexÚ75Ú82rŸ   Nr„   )r%   r   Úfinancial_findingsÚfindingÚmarket_findingsÚ	kpi_tabler‰   Úkpisri   ÚkpiÚtargetÚactualÚstatusr   r'   r'   r(   r0   ,  sR   üûüü






r0   c                 C   s¨  | j ddd | di ¡}| j ddd |  d ¡ ¡ |  ¡  | j dd	d g d
¢}|D ]	}| j|dd q,|  ¡  | j dd	d | jddd}d|_|jd j}d|d _d|d _d|d _d|d	 _d|d _t	|ƒ g d¢}t
|dƒD ](\}\}	}
}}}|j| j}|	|d _|
|d _||d _||d	 _||d _qw|  ¡  | j ddd |  d ¡ ¡ |  ¡  | jdd	d}d|_|jd j}d|d _d|d _d|d _t	|ƒ g d¢}t
|dƒD ]\}\}}}|j| j}||d _||d _||d _qâ|  ¡  | j d dd |  d! ¡ ¡ g d"¢}|D ]\}}|  ¡ }d#| |d$ ¡_| |¡ q|  ¡  |rN| ¡ D ]\}}| j |dd |rLt| |ƒ q9|  ¡  d%S )&z:Add detailed analysis with clean markdown header handling.zDetailed Analysisr   r9   r   zMarket Analysisr>   zë
    The market landscape presents significant opportunities balanced against competitive 
    challenges. Analysis indicates sustained demand across core markets with particular 
    strength in emerging segments and geographies.
    zMarket Dynamicsrt   )z9Total addressable market estimated at $85B with 5-7% CAGRz;Market consolidation creating economies of scale advantageszCDigital disruption enabling new business models and revenue streamszCRegulatory environment stable with moderate compliance requirementszICustomer preferences shifting toward sustainable and innovative solutionsro   rp   zCompetitive Landscapeé   rG   rr   r   Ú
Competitorr€   úGrowth RatezKey StrengthzKey Weaknessrq   ))zOur Companyr   z11.8%Ú
InnovationÚScale)zCompetitor Az14.2%z8.3%ÚDistributionÚDigital)zCompetitor Bz12.5%z9.1%zCost Positionr®   )zCompetitor Cz10.3%z6.8%Ú
GeographicÚ
TechnologyzOperational Performancezà
    Operational metrics reflect strong execution across all functions. Supply chain 
    optimization, manufacturing efficiency, and quality improvements contribute to 
    competitive advantage and margin enhancement.
    é   zOperational MetricÚCurrentzTrend vs Prior))zManufacturing Efficiencyz94.5%u   â†‘ +230 bps)zSupply Chain Costsz8.2% of revenueu   â†“ -120 bps)zQuality Defect Ratez0.8%u   â†“ -40 bps)zAsset Utilizationz87%u   â†‘ +300 bps)zEnergy Efficiencyz15% reductionõ   â†‘ Improved)zWaste Reductionz22% decreaser¶   )zSafety Incident Ratez0.3 per 100k hrsu   â†“ -50%zStrategic InitiativeszÈ
    Multiple strategic initiatives underway to drive growth and competitive positioning. 
    Programs span digital transformation, innovation, market expansion, and operational 
    excellence.
    ))úDigital Transformationz<Investing $150M over 3 years in cloud, AI/ML, and automation)zInnovation Pipelinez615+ major product launches planned over next 24 months)zMarket Expansionz>Entering 8 new geographic markets with $500M revenue potential)úM&A Strategyz;Active pipeline of bolt-on acquisitions in adjacent markets)ÚSustainabilityz<Target: carbon neutral by 2030, 40% renewable energy by 2025Tú: N)rN   ÚgetrV   r…   rW   rY   rH   rZ   r[   r\   r]   r^   ÚboldÚitemsÚ_render_content_cleanra   )r%   r   Úsections_dataÚmarket_dynamicsÚitemÚ
comp_tabler‰   Úcompetitorsri   ÚcompÚshareÚgrowthÚstrengthÚweaknessr   Ú
perf_tableÚ
op_metricsr‹   rŒ   ÚtrendÚinitiativesrb   Údescriptionr›   Úsection_nameÚcontentr'   r'   r(   r1   ‹  s†   ü








ü





ü
€r1   c                 C   sf  | j ddd |  d ¡ ¡ |  ¡  | j ddd |  d ¡ ¡ |  ¡  | jdd	d
}d|_|jd j}d|d _d|d _d|d _d|d _d|d _t|ƒ g d¢}t	|dƒD ](\}\}}}}	}
|j| j}||d _||d _||d _|	|d _|
|d _qZ|  ¡  | j ddd |  d ¡ ¡ |  ¡  | jddd
}d|_|jd j}d|d _d|d _d|d _d|d _t|ƒ g d¢}t	|dƒD ]"\}\}}}}|j| j}||d _||d _||d _||d _qÊ|  ¡  | j ddd |  d ¡ ¡ |  ¡  | jddd
}d|_|jd j}d|d _d|d _d |d _t|ƒ g d!¢}t	|dƒD ]\}\}}}
|j| j}||d _||d _|
|d _q/|  ¡  | j d"dd |  d# ¡ ¡ |  ¡  | jddd
}d|_|jd j}d$|d _d|d _d%|d _t|ƒ g d&¢}t	|dƒD ]\}\}}}|j| j}||d _||d _||d _q|  
¡  d'S )(z9Add comprehensive financial metrics section (8-10 pages).zFinancial Metrics Analysisr   r9   z”
    Comprehensive financial analysis examining revenue composition, profitability trends, 
    cash flow dynamics, and balance sheet strength.
    zRevenue Analysisr>   zÉ
    Revenue growth driven by balanced contribution from volume, price, and mix. Core 
    business remains stable while growth initiatives contribute disproportionately to 
    overall expansion.
    r”   r«   rG   rr   r   zRevenue SegmentzCurrent ($B)z
Prior ($B)úGrowth %rt   ú
% of Totalrq   ))zCore Businessz4.2z3.9z+7.7%z49.4%)zGrowth Productsz2.8z2.3z+21.7%z32.9%)zEmerging Marketsz1.1z0.9z+22.2%z12.9%)ÚServicesz0.4z0.35z+14.3%z4.8%)zTotal Revenuez8.5z7.6rv   z100.0%zProfitability Metricszn
    Profitability improved across all measures reflecting operational leverage and cost 
    management.
    é   zProfitability Metricrs   ))ru   z8.50z7.60rv   )zGross Profitz3.40z2.95z+15.3%)rw   z1.59z1.23rx   )r{   z2.10z1.78r|   )ry   z1.12z0.89rz   )zDiluted EPSz$4.15z$3.28z+26.5%zCash Flow Analysisz^
    Strong cash generation continues with operating cash flow growth outpacing earnings.
    r´   zCash Flow ComponentzAmount ($B)z% of Revenue))zOperating Cash Flowz2.15z25.3%)zCapital Expendituresz(0.85)z(10.0%))r   z1.30z15.3%)zDividends Paidz(0.55)z(6.5%))zShare Buybacksz(0.40)z(4.7%))zDebt Repaymentz(0.20)z(2.4%))zNet Cash Flowz0.15z1.8%zBalance Sheet StrengthzV
    Balance sheet remains strong with healthy liquidity and manageable leverage.
    zBalance Sheet MetriczRatio/Comment))zTotal Assetsz12.5zAsset turnover: 0.68x)zCash & Equivalentsz1.8z21% of total assets)z
Total Debtz3.2zDebt/EBITDA: 1.5x)zShareholders' Equityz5.5zEquity ratio: 44%)zWorking Capitalú2.1zCurrent ratio: 1.8x)zNet Debtz1.4zNet leverage: 0.7xNr„   )r%   r   Ú	rev_tabler‰   Úrevenue_segmentsri   ÚsegmentrŒ   r   rÆ   Úpctr   Úprofit_tableÚprofit_datar‹   rŽ   Úcf_tableÚcf_dataÚ	componentÚamountÚbs_tableÚbs_dataÚratior'   r'   r(   r2     s®   ýü








ý



	


þ





þ


	

r2   c                 C   s’  | j ddd |  d ¡ ¡ |  ¡  | j ddd | j ddd |  d	 ¡ ¡ |  ¡  | jd
dd}d|_|jd j}d|d _d|d _t|ƒ g d¢}t	|dƒD ]\}\}}|j| j}||d _||d _qR|  ¡  | j ddd |  d ¡ ¡ |  ¡  | jddd}	d|	_|	jd j}d|d _d|d _t|ƒ g d¢}
t	|
dƒD ]\}\}}|	j| j}||d _||d _q¦|  ¡  | j ddd | jddd}d|_|jd j}d|d _d|d _d|d _d|d _t|ƒ g d¢}t	|dƒD ]"\}\}}}}|j| j}||d _||d _||d _||d _qù|  ¡  | j ddd |  d ¡ ¡ |  ¡  g d¢}|D ]
}| j|d d! q8|  
¡  d"S )#z3Add company/segment profiles section (10-12 pages).zCompany & Segment Profilesr   r9   zQ
    Detailed analysis of major business segments and operational divisions.
    zBusiness Segment Overviewr>   zTechnology & Digital Servicesrt   z`
    Leading provider of technology solutions and digital services to enterprise customers.
    é
   rG   rr   r   Ú	AttributeÚDetails)	)úMarket PositionzMarket leader with 18.5% share)úRevenue (Current)z$2.8B (32.9% of total))zRevenue (Prior)z$2.3B)r­   z
+21.7% YoY)r}   z24.5%)úKey Productsz&Cloud, AI/ML, Cybersecurity, Analytics)úCustomer Basez500+ enterprise customers)zGeographic PresencezNA (60%), EU (25%), APAC (15%))zCompetitive Advantagez+Innovation leadership, integrated solutionszFinancial Servicesza
    Comprehensive financial services including banking, insurance, and investment products.
    rL   ))rå   zTop 3 player with 12.3% share)ræ   z$2.1B (24.7% of total))r­   z
+10.5% YoY)r}   z18.2%)rç   zBanking, Insurance, Investment)rè   z2.1M+ retail, 15K+ SMB)zAssets Under Managementz$48B (+12% YoY))zDigital Adoptionz65% of transactions digitalzGeographic Analysisr«   rq   ÚRegionzRevenue ($B)rÐ   rÑ   ))zNorth Americaz4.3z+9.5%z50.6%)ÚEuroperÔ   z+8.2%z24.7%)zAsia Pacificz1.5z+22.0%z17.6%)zRest of Worldz0.6z+15.4%z7.1%zProduct Portfoliozc
    Diversified product portfolio spanning multiple categories with strong brand recognition.
    )zDPremium Products: High-margin offerings targeting affluent customerszDStandard Products: Core mainstream products with broad market appealzGValue Products: Cost-competitive offerings for price-sensitive segmentszFDigital Services: Software, platforms, and subscription-based serviceszGProfessional Services: Consulting, implementation, and support servicesro   rp   Nr„   )r%   r   Ú
seg1_tabler‰   Ú	seg1_datari   ÚattrÚdetailr   Ú
seg2_tableÚ	seg2_dataÚ	geo_tableÚgeo_dataÚregionÚrevenuerÆ   rØ   Úproduct_categoriesÚcategoryr'   r'   r(   r3   ®  s„   þþ


þ









þr3   c                 C   sê  | j ddd |  d ¡ ¡ |  ¡  | j ddd | jddd	}d
|_|jd j}d|d _d|d _d|d _d|d _d|d _t|ƒ g d¢}t	|dƒD ]G\}\}}}}	}
|j| j}||d _||d _||d _|	|d _|	dkr~t
|d dƒ n|	dkrŠt
|d dƒ nt
|d dƒ |
|d _qO|  ¡  | j ddd | j ddd g d¢}|D ]	}| j|dd q¯|  ¡  | j ddd g d¢}|D ]	}| j|dd qÊ|  ¡  | j d dd g d!¢}|D ]	}| j|dd qå|  ¡  d"S )#z.Add comprehensive risk assessment (5-6 pages).zRisk Assessmentr   r9   zJ
    Comprehensive assessment of key risks and mitigation strategies.
    zRisk Categoriesr>   rL   r«   rG   úMedium Grid 1 Accent 1r   zRisk CategoryÚProbabilityÚImpactz
Risk Levelrt   ÚTrendrq   ))zRegulatory & ComplianceÚMediumÚHighrü   õ   â†‘ Increasing)zMarket Competitionrü   rû   rü   õ
   â†’ Stable)zTechnology Disruptionrû   rü   rü   rý   )ÚCybersecurityrû   rü   rü   rý   )zEconomic DownturnÚLowrü   rû   rþ   )zSupply Chainrû   rû   rû   u   â†“ Decreasing)zTalent Retentionrû   rû   rû   rþ   )zClimate Changer   rû   r   rý   rü   ÚFFC8C8rû   ÚFFFFC8ÚC8FFC8zMitigation StrategieszRegulatory & Compliance Risk)z3Dedicated compliance team with regulatory expertisez-Regular compliance audits and control testingz$Proactive engagement with regulatorsz2Investment in compliance technology and automationz'Ongoing training programs for employeesro   rp   zMarket Competition Risk)z(Continuous innovation and R&D investmentz2Strong customer relationships and service deliveryz9Operational efficiency enabling competitive cost positionz(Brand building and marketing investmentsz0Strategic partnerships and ecosystem developmentzTechnology Disruption Risk)z4Significant IT and digital transformation investmentz(Innovation labs and venture partnershipsz-Cloud-first strategy with modern architecturez,Talent acquisition in key technology domainsz*Continuous monitoring of technology trendsN)rN   rV   r…   rW   rY   rH   rZ   r[   r\   r]   Ú_set_cell_colorra   )r%   r   Ú
risk_tabler‰   Úrisksri   rö   ÚprobÚimpactr:   rË   r   Úreg_mitigationsÚ
mitigationÚcomp_mitigationsÚtech_mitigationsr'   r'   r(   r4   2  sZ   þ








r4   c                 C   sV  | j ddd |  d ¡ ¡ |  ¡  | j ddd | j ddd g d	¢}|D ]	}| j|d
d q&|  ¡  | j ddd g d¢}|D ]	}| j|d
d qA|  ¡  | j ddd | j ddd g d¢}|D ]	}| j|d
d qc|  ¡  | j ddd g d¢}|D ]	}| j|d
d q~|  ¡  | j ddd | j ddd g d¢}|D ]	}| j|d
d q |  ¡  | j ddd g d¢}|D ]	}| j|d
d q»|  ¡  | j ddd | jddd}	d|	_|	jd j}
d|
d _d|
d _d |
d _d!|
d _t|
ƒ g d"¢}t	|dƒD ]#\}\}}}}|	j| j}||d _||d _||d _||d _q|  
¡  d#S )$z2Add strategic recommendations section (5-7 pages).zStrategic Recommendationsr   r9   z]
    Strategic recommendations to enhance competitive positioning and accelerate growth.
    zGrowth Initiativesr>   z$1. Accelerate Digital Transformationrt   )z@Establish digital transformation office with C-level sponsorshipz9Develop comprehensive digital strategy and 3-year roadmapz7Invest $450-500M over 3 years in cloud, data, and AI/MLz2Develop digital talent through hiring and trainingz3Implement agile operating model across organizationz<Launch customer-facing digital products in priority segmentsro   rp   z 2. Geographic Expansion Strategy)z4Prioritize expansion in high-growth emerging marketsz/Establish local partnerships and joint venturesz;Develop localized products tailored to regional preferencesz9Build distribution networks and go-to-market capabilitiesz3Invest $200-300M over 3 years in market developmentz=Target 15-20% market share in priority markets within 5 yearszOperational Excellencez.3. Manufacturing and Supply Chain Optimization)z9Implement lean manufacturing principles across facilitiesz3Automate repetitive processes to improve efficiencyz-Optimize supply chain with advanced analyticsz8Reduce inventory levels while maintaining service levelsz/Improve supplier collaboration and partnershipsz.4. Quality and Customer Experience Enhancement)z$Implement Six Sigma quality programsz1Enhance customer support and service capabilitiesz-Develop customer feedback loops and analyticsz*Improve product quality and reduce defectsz2Build customer-centric culture across organizationzInvestment Prioritiesz 5. Innovation and R&D Investment)z(Increase R&D spending to 6-7% of revenuez+Establish innovation centers in key marketsz&Partner with startups and universitiesz.Target 5-7 major new product launches annuallyz'Enhance intellectual property portfolioz!6. M&A and Portfolio Optimization)z4Develop M&A strategy focused on bolt-on acquisitionsz(Build corporate development capabilitiesz$Target 2-3 acquisitions over 3 yearsz4Focus on technology and specialty product categoriesz4Maintain financial discipline with clear ROI hurdleszImplementation RoadmaprÓ   rq   rG   r÷   r   ÚRecommendationÚTimelinezInvestment ($M)ÚPriority))r·   z3 yearsz450-500rü   )zGeographic Expansionz	3-5 yearsz200-300rû   )zSupply Chain Optimizationz2 yearsz100-150rü   )zQuality EnhancementÚ
Continuousz
50-75/yearrû   )zInnovation & R&Dr  z150-200/yearrü   )r¸   ÚOngoingz	500-1,000rü   Nr„   )r%   r   Úactions1ÚactionÚactions2Úactions3Úactions4Úactions5Úactions6Úroadmap_tabler‰   Úroadmapri   ÚrecÚtimelineÚ
investmentÚpriorityr   r'   r'   r(   r5   “  sn   þ



	


r5   c                 C   sª  | j ddd |  d ¡ ¡ |  ¡  | j ddd d|v r}|d r}| jt|d ƒd dd	}d
|_|jd j}d|d _d|d _d|d _d|d _t	|ƒ t
|d dƒD ]%\}}t|ƒj}|j| j}t|ƒ|d _||d _d|d _d|d _qVn|  d¡ |  ¡  | j ddd |  d ¡ ¡ |  ¡  g d¢}|D ]\}	}
|  ¡ }d| |	d ¡_| |
¡ qž|  ¡  | j ddd g d¢}|D ]	}| j|dd qÅ|  ¡  dS )z,Add source traceability section (3-4 pages).zSource Traceabilityr   r9   zI
    Complete traceability of data sources and analysis methodology.
    zSource Documentsr>   rB   rq   rG   rr   r   rJ   rK   zDocument TypezPeriod Coveredrt   zAnnual ReportzFY 2024z#Source document list not available.zAnalysis Methodologyzo
    Analysis conducted using rigorous methodology combining quantitative and qualitative 
    techniques:
    ))zDocument Reviewz,Comprehensive review of all source documents)zData Extractionz1Systematic extraction of key metrics and insights)zFinancial Analysisz.Detailed financial modeling and ratio analysis)ÚBenchmarkingz<Comparison against industry peers and historical performance)Ú
Validationz6Cross-reference and validation across multiple sources)Ú	Synthesisz4Integration of quantitative and qualitative insightsTrº   zData Quality & Limitations)z0Analysis based on publicly available informationz1Forward-looking statements subject to uncertaintyz0Industry benchmarks based on peer group averagesz9Qualitative assessments incorporate professional judgmentz7Historical performance not indicative of future resultsro   rp   N)rN   rV   r…   rW   rX   rY   rH   rZ   r[   r\   r]   r   rC   r#   r^   r¼   ra   )r%   r   Ú
docs_tabler‰   ri   Údoc_pathrj   r   Úmethodology_stepsÚsteprÍ   r›   ÚlimitationsÚ
limitationr'   r'   r(   r6     sR   þ






ú
ý	r6   c                 C   sp  | j ddd |  d ¡ ¡ |  ¡  | j ddd g d¢}|D ]	}| j|dd	 q|  ¡  | j d
dd |  d ¡ ¡ |  ¡  | j ddd | jddd}d|_|jd j}d|d _d|d _d|d _t|ƒ g d¢}t	|dƒD ]\}\}}	}
|j| j}||d _|	|d _|
|d _qr|  ¡  |  ¡  |  ¡ }t
j|_| d¡}d|_tdƒ|j_tdddƒ|jj_dS )z%Add conclusion WITHOUT AI disclaimer.zConclusion & Outlookr   r9   z¤
    Comprehensive analysis reveals an organization with strong fundamentals, clear strategic 
    direction, and significant opportunities for value creation.
    zSummary of Key Findingsr>   )zBStrong financial performance exceeding targets and peer benchmarksz9Market leadership with demonstrated ability to gain sharez-Successful execution of strategic initiativesz;Robust operational performance with efficiency improvementsz6Healthy financial position with strong cash generationz5Clear strategic priorities aligned with opportunitiesz4Effective risk management with mitigation strategiesro   rp   zStrategic Outlookz¹
    The organization is well-positioned for continued success. Key drivers include market 
    leadership, innovation capabilities, digital transformation, and financial strength.
    zExpected Value Creationr”   rt   rG   rr   r   Ú
Initiativez3-Year TargetzValue Creation))zRevenue Growthz+35-40%z$3.0-3.4B incremental)zMargin Expansionz+300-400 bpsz$400-550M EBITDA)zM&A Contributionz	$400-600MzStrategic capabilities)r   z+40-50%z$1.8-2.0B annual)zShareholder Returnsz15-18% CAGRzTop quartile TSRu   â€” End of Report â€”Té   r<   r=   N)rN   rV   r…   rW   rY   rH   rZ   r[   r\   r]   r   rO   rP   r^   r¼   r   rR   rS   r   rT   rU   )r%   r   Úsummary_findingsr£   Úvalue_tabler‰   Ú
value_datari   Ú
initiativer¨   Úvaluer   ÚfooterÚ
footer_runr'   r'   r(   r7   c  sJ   ý	ý





r7   r*   r,   c                 C   sH   t | ƒ}||k r || }t|ƒD ]}|  ¡  |  d¡ |  ¡  qdS dS )zƒ
    Ensures document reaches target page count by adding filler pages.
    Uses explicit page breaks to guarantee page count.
    ú N)Ú_count_forced_pagesÚrangerV   ra   )r%   r,   Úcurrent_pagesÚpages_to_addÚir'   r'   r(   r8   ³  s   

ùr8   c                 C   s   | j j}|j}| d¡d S )z'Count explicit page breaks in document.zw:type="page"r   )Ú_elementÚbodyÚxmlÚcount)r%   r8  r9  r'   r'   r(   r2  Ä  s   r2  rÏ   c                 C   s†  |sdS |  d¡}g }|D ]Ÿ}| ¡ }| d¡r;|r*d |¡ ¡ }|r(t| |ƒ g }| d¡ ¡ }|r:| j|dd q| d¡rc|rRd |¡ ¡ }|rPt| |ƒ g }| d¡ ¡ }|rb| j|dd q| d¡r| d¡s|rd |¡ ¡ }|r}t| |ƒ g }| d¡ ¡ }|r| j|d	d q|d
kr§|r¦d |¡ ¡ }|r¤t| |ƒ g }q| |¡ q|r¿d |¡ ¡ }|rÁt| |ƒ dS dS dS )z3Render content with clean markdown header handling.NÚ
z###ú#rt   r9   z##r>   r   Ú )Úsplitr…   r—   ÚjoinÚ_add_paragraph_or_listÚlstriprN   Úappend)r%   rÏ   ÚlinesÚcurrent_paragraph_linesrš   Úline_strippedÚ	para_textÚheader_textr'   r'   r(   r¾   Ð  sd   


€

€
€
€ýr¾   r[   c                 C   s  |  ¡ }|sdS | d¡s| d¡s| d¡r?| d¡}|D ]}|  ¡ r<|  ¡  d¡  ¡ }|r<| j|dd}td	ƒ|j_qdS t 	d
|¡rd| d¡}|D ]}|  ¡ ra| j|  ¡ dd}td	ƒ|j_qLdS d|v rv| 
d¡dkrvt| |ƒ dS |  |¡}tdƒ|j_d|j_dS )zAdd text as paragraph or list.Nú-u   â€¢Ú*r;  u   -â€¢*ro   rp   rq   z^\d+\.zList Numberú|rt   râ   gffffffò?)r…   r—   r>  rA  rV   r   r•   r–   ÚreÚmatchr:  Ú_render_markdown_tableÚline_spacing)r%   r[   rC  rš   Ú
clean_liner›   r'   r'   r(   r@    s4   
€û
€ý
r@  Úfindings_datac              	   C   sÆ  |  dg ¡}t|  dg ¡ƒ}| jddd}tj|_tdƒ|jd j_	t
dddƒ|jd jj_|  ¡  |  d	t› ¡}tj|_td
ƒ|jd j_	|  dt|ƒ› ¡}tj|_|  ¡  | jddd | jtd
t|ƒƒd dd}d|_|jd j}d|d _d|d _d|d _t|ƒ t|dd
… dƒD ])\}	}
|j|	 j}|
  dd¡dd… |d _|
  dd¡|d _|
  dd¡|d _q“|  ¡  | jddd | jddd}d|_|jd j}d|d _d|d _d|d _d|d _d |d! _t|ƒ d}|D ]p}
|
  d"¡|v ri| ¡ j}t|ƒ|d _|
  d"d¡|d _|
  dd¡}t|ƒdkr-|dd… d# n||d _|
  dd¡|d _t|
  d$d¡ƒ|d! _|
  d¡d%krVt|d d&ƒ n|
  d¡d'kret|d d(ƒ |d7 }qù|  ¡  i }|D ]}
|
  dd)¡}| |g ¡ |
¡ qr| ¡ D ]Ñ\}}| j|dd |D ]¾}
|  ¡ }| d*|
  dd¡› ¡}d+|_ td,ƒ|j_	| jd-d.}| d/|
  dd¡› d0¡ | d1|
  d2d¡› d0¡ | d3|
  d$d¡› ¡ |
  d4g ¡}|rO| jt|ƒd dd}d5|_|jd j}d6|d _d7|d _d8|d _t|ƒ t|dƒD ]<\}}|j| j}t!|  d9d:¡ƒj"|d _t|  d;d<¡ƒ|d _|  d=d¡}t|ƒd>krH|dd>… d# n||d _q|  ¡  q–|  ¡  q‰t#| d?d@ dS )AzRender findings-based report.r   Ú
top_10_idszAnnual Report Findingsr   r9   r;   r<   r=   zRun ID: râ   zTotal Findings: rn   r   rt   rG   rr   ÚFindingÚSeverityÚCategoryr>   Nr£   zN/AéP   Úseverityrö   zTop 10 Key Risksr«   zMedium Grid 3 Accent 1ÚRankÚIDÚScorerq   Úidz...Úscorerü   r  rû   r  ÚOtheru   âš« Té   ro   rp   z
Severity: z | zConfidence: Ú
confidencezScore: ÚevidencezLight Shading Accent 1r   ÚPageÚQuoterj   ÚUnknownÚpageÚ?Úquoteéd   r*   r+   )$r»   ÚsetrN   r   rO   rP   r   rQ   rR   rS   r   rT   rU   rV   r   rX   ra   rW   ÚminrY   rH   rZ   r[   r\   r]   Úadd_rowr#   r  Ú
setdefaultrB  r½   r^   r¼   r   rC   r8   )r%   rP  r   rQ  rb   r›   Ú
total_pararˆ   r‰   ri   Úfr   r  ÚrankÚfinding_textÚgroupedÚcatrö   r½   Úfinding_paraÚfinding_runrl   Úevidence_listÚev_tableÚev_hdrÚev_idxÚeÚev_rowÚ
quote_textr'   r'   r(   r   0  s®   








(€


,r   c              	   C   sÔ   | D ]e}zZ|j r4|j d jr4d|j d jd j_tdƒ|j d jd j_tdddƒ|j d jd jj_n$|j rX|j	}d|_	|j d  
|¡}d|j_tdƒ|j_tdddƒ|jj_t|dƒ W q tyg   Y qw dS )z1Apply professional styling to table header cells.r   Tr]  éÿ   r=  Ú003366N)Ú
paragraphsrQ   rR   r¼   r   rS   r   rT   rU   r[   r^   r  Ú	Exception)Úheader_cellsÚcellr[   Úrunr'   r'   r(   r\   ©  s$    ÿñr\   Ú	hex_colorc                 C   sH   zt dƒ}| tdƒ| ¡ ¡ | j ¡  |¡ W dS  ty#   Y dS w )z$Set background color for table cell.zw:shdzw:fillN)r	   rg  r   Úupperr7  Úget_or_add_tcPrrB  r}  )r  r  Úshading_elmr'   r'   r(   r  ¾  s   ÿr  Útable_mdc                 C   sr  z§dd„ |  ¡  d¡D ƒ}t|ƒdk rW dS dd„ |d  d¡D ƒ}g }|d	d… D ]}d
d„ | d¡D ƒ}|r=| |¡ q*|rB|sEW dS | jt|ƒd t|ƒd}d|_|jd j}t|ƒD ]\}	}
|	t|ƒk rn|
||	 _	q_t
|ƒ t|ƒD ]-\}	}|	d t|jƒk r¤t|ƒD ]\}}|t|j|	d  jƒk r£||j|	d  j| _	qˆqwW dS  ty¸   | j|dd Y dS w )z$Render markdown table as Word table.c                 S   ó   g | ]
}|  ¡ r|  ¡ ‘qS r'   ©r…   )rD   rš   r'   r'   r(   rF   Ë  ó    z*_render_markdown_table.<locals>.<listcomp>r;  rt   Nc                 S   r†  r'   r‡  ©rD   r  r'   r'   r(   rF   Ð  rˆ  r   rJ  r>   c                 S   r†  r'   r‡  r‰  r'   r'   r(   rF   Ô  rˆ  r   rG   rr   z
No Spacingrp   )r…   r>  rX   rB  rW   rY   rH   rZ   r]   r[   r\   r}  rV   )r%   r…  rC  ÚheadersrH   rš   rZ   Útablerh   r6  Úheaderr   ÚjÚ	cell_textr'   r'   r(   rM  È  s>   
€
€€üÿrM  Úfilepathc                 C   s‚   |   ¡ s| S | j}| j}| j}d}	 ||› d|› |›  }|  ¡ s#|S |d7 }|dkr@ddl}t| ¡ ƒ}||› d|› |›  S q)z(Generate unique filename if file exists.r   TÚ_iè  r   N)Úexistsr   ÚstemÚsuffixÚtimeÚint)r  Ú	directoryr’  r“  ÚcounterÚnew_pathr”  Ú	timestampr'   r'   r(   r   ï  s    ÷r   ú'Consolidated_Annual_Report_Summary.docxc                 C   s
   t | |ƒS )z*Legacy function - backwards compatibility.)r)   )rP  r   r'   r'   r(   Úrender_findings_docx  s   
r›  )r   )r*   )rš  )0ÚosÚpathlibr   Údocxr   Údocx.sharedr   r   r   Údocx.enum.textr   Údocx.oxml.nsr   Ú	docx.oxmlr	   Útypingr
   r   rK  Ú
rag.configr   r   Údictr#   r)   r   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r•  r8   r2  r¾   r@  r   r\   r  rM  r   r›  r'   r'   r'   r(   Ú<module>   sL    /6g,_  " a MP=#y
'