o
    `Ai/                      @   s   d dl Z d dlmZmZ d dlmZ d dlmZ d dlm	Z	 ee	j
dZdded	ed
efddZdeded
eeef fddZdS )    N)DictList)OpenAI)embed_query)config)api_keyd   querykreturnc                 C   s   t |}| j||d}i }|D ]1}|d }|dd}|d|}	||vr,|	g d||< || d |dd	|d
dd qt||}
|dd | D |
dS )zk
    Build a comprehensive 20-25 page report.
    Increased retrieval and detailed section generation.
    )r
   metadatadoc_idUnknowndoc_name)r   chunksr   page_number?text )pager   c                 S   s   g | ]}|d  qS )r    ).0infor   r   @/var/www/html/fyndo/python/python_agents/rag_suite/rag/report.py
<listcomp>*   s    z+build_report_from_query.<locals>.<listcomp>)r	   docssections)r   searchgetappend&generate_comprehensive_report_sectionsvalues)storer	   r
   qvechits
doc_chunkshitmetar   r   r   r   r   r   build_report_from_query   s(   




r(   r%   c                 C   s  i }d}|   D ]7\}}|dd d7 }|d|d  d7 }|d d7 }|d dd	 D ]}|d
|d  d|d  d7 }q-q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dddddd
}|  D ]e\}}	td| d d| d|dd   d!| d"|	d#  d$	}
ztjjjtjd%|
d&gd'|	d( d)}|jd* j	j
 ||< W qo ty } ztd+| d,|  d-t| ||< W Y d}~qod}~ww |S ).z
    Generate detailed, comprehensive report sections for 20-25 pages.
    Each section gets more tokens and detailed instructions.
    r   z

z<============================================================
z
DOCUMENT: r   r   N   z[Page r   z]
r   aU  Provide a comprehensive executive summary (2-3 pages) that includes:
- Overview of all companies analyzed
- Key highlights and major findings
- Critical risks and opportunities
- Overall financial health assessment
- Strategic recommendations
Be detailed and professional. Include specific numbers, percentages, and facts from the documents.i  )instruction
max_tokensa)  Provide detailed company overview including:
- Company history and establishment
- Business model and operations
- Market position and competitors
- Geographic presence and facilities
- Key milestones and achievements
- Corporate structure
Provide 2-3 paragraphs per company with specific details.a  Provide comprehensive analysis of leadership:
- Board of Directors: names, designations, qualifications
- Key Management Personnel with roles
- Management changes during the year
- Experience and expertise of leadership team
- Board composition (independent vs executive directors)
- Board committees and their roles
Present in detailed narrative form with specific names and positions.aC  Detailed shareholding analysis including:
- Promoter shareholding with exact percentages
- Institutional investors and their stakes
- Public shareholding breakdown
- Changes in shareholding during the year
- Top 10 shareholders if available
- Any pledge or encumbrance of shares
Present specific numbers and analyze trends.al  Comprehensive financial analysis covering:
- Revenue trends over 3-5 years with specific numbers
- Profitability metrics (PAT, EBITDA margins)
- Cash flow analysis
- Balance sheet highlights (assets, liabilities, equity)
- Key financial ratios
- Year-over-year growth rates
- Comparison with previous years
Provide detailed numerical analysis with interpretations.i  a]  Detailed operational analysis:
- Core business activities and products/services
- Production capacity and utilization
- Market segments served
- Sales and distribution channels
- Technology and R&D initiatives
- Strategic partnerships and collaborations
- Expansion plans and capital expenditure
Provide comprehensive details with specific examples.a'  Comprehensive risk analysis including:
- Business and operational risks
- Financial risks (credit, liquidity, market)
- Regulatory and compliance risks
- Industry-specific risks
- Mitigation strategies for each risk
- Risk management framework
Provide detailed explanation of each risk category.a0  Detailed governance analysis:
- Corporate governance framework
- Board meetings and attendance
- Audit committee and other committees
- Internal controls and compliance
- Related party transactions
- Code of conduct policies
- Stakeholder engagement
Provide comprehensive details on governance practices.a3  Detailed compliance and legal analysis:
- Regulatory framework applicable
- Compliance status with key regulations
- Legal proceedings if any
- Statutory auditor observations
- Secretarial audit findings
- Penalties or fines if any
- Compliance certifications
Provide specific details on compliance matters.a8  Comprehensive forward-looking analysis:
- Industry trends and outlook
- Company's strategic initiatives
- Growth opportunities and challenges
- Management's future plans
- Analyst recommendations
- Potential catalysts for growth
- Key monitoring points for stakeholders
Provide detailed forward-looking insights.)
z1. Executive Summaryz 2. Company Overview & Backgroundz3. Directors & Managementz#4. Shareholding Pattern & Ownershipz!5. Financial Performance Analysisz!6. Business Operations & Strategyz7. Risk Assessment & Managementz8. Corporate Governancez 9. Regulatory Compliance & Legalz$10. Future Outlook & Recommendationsz  Generating: z...zbYou are a professional financial analyst writing a detailed annual report section.

Report Query: z9

Context from documents (use ALL relevant information):
i:  z

Section: z

Task: r+   a  

IMPORTANT:
- Be comprehensive and detailed
- Use specific facts, numbers, and names from the documents
- Cite sources as [Document Name, Page X]
- Write in professional, formal language
- Aim for 2-3 pages of content per section
- Include all relevant details found in the context
- Do not write "based on the context" or similar meta-commentary
- Write as if you are directly presenting the findings

Output:user)rolecontentg333333?r,   )modelmessagestemperaturer,   r   u     ⚠️ Error generating z: zError generating this section: )itemsprintclientchatcompletionscreater   	LLM_MODELchoicesmessager/   strip	Exceptionstr)r%   r	   r   full_contextr   r   chunksection_promptssection_nameconfig_dictpromptresponseer   r   r   r    /   s    					
	
r    )r   )jsontypingr   r   openair   rag.qar   ragr   OPENAI_API_KEYr5   r>   intr(   r    r   r   r   r   <module>   s   "$