U
    h(                     @   sv   d dl mZmZmZmZ d dlmZmZ d dlZd dl	Z	d dl
Z
d dlmZ d dlmZmZmZmZ G dd dZdS )    )capture_exceptioncapture_messageset_tagset_context)monitor_azure_apimonitor_critical_systemN)BeautifulSoup)AZURE_DEVOPS_URLAZURE_DEVOPS_ORGAZURE_DEVOPS_PROJECTAZURE_DEVOPS_PATc                   @   sD   e Zd ZdddZedddZedddZdeed	d
dZ	dS )AzureClientNc                 C   sX  t d|  |r|dt| _|dt| _|dt| _|dt| _	t d| j d| j d| j d	| j	rzd
t
| j	 nd  n^|pt| _|pt| _d | _|pt| _	t d| j d| j d| j d	| j	rd
t
| j	 nd  d | _| jr*t| jtr*| jdsd| j | _| jd| _n*t| jtsTt dt| j d d | _d S )Nu7   🔧 AzureClient constructor called with: azure_config=urlorgprojectpatu    🔧 Using azure_config - URL: '	', Org: '', Project: '', PAT: *Noneu!   🔧 Using direct params - URL: ')zhttp://https://r   /u   ❌ Invalid azure_url type: z, expected string)printgetr	   	azure_urlr
   	azure_orgr   azure_projectr   	azure_patlen
last_error
isinstancestr
startswithrstriptype)selfr   r   r   azure_config r(   K/var/www/html/testcasegenerator.evdpl.com/azure_integration/azure_client.py__init__   s(    <


:zAzureClient.__init__c                    s  |s$t ddd}dd |D }|s4td d S td| j d| j d	| j d
| jrddt| j nd  | jsd| _	td d S | jsd| _	td d S | jsd| _	td d S | jsd| _	td d S g }d}ddt
d| j    d dd }tdt||D ]}||||  }ddd |D }| j d| j d| j d| d ztd!d" fd#d$}| }	|	jdkr|	 pi }
|
d%g }|D ]N}t|d&}|d'i }|d(d)}|d*d+}|||||d, qtd-t| d. n&d/|	j }|| _	td0| d1|  W n` tk
r } z@d2t| }|| _	td0|  t||| j| j| jd3 W 5 d }~X Y nX q|S )4NZAZURE_DEVOPS_WORKITEM_IDS ,c                 S   s   g | ]}|  r|  qS r(   )strip).0idr(   r(   r)   
<listcomp>0   s      z6AzureClient.fetch_azure_work_items.<locals>.<listcomp>uW   ⚠️ Work item IDs not found. Please set AZURE_DEVOPS_WORKITEM_IDS in your .env file.u%   🔍 Validating Azure fields - URL: 'r   r   r   r   r   z Azure DevOps URL cannot be emptyu$   ❌ Azure DevOps URL cannot be emptyz)Azure DevOps organization cannot be emptyu-   ❌ Azure DevOps organization cannot be emptyz$Azure DevOps project cannot be emptyu(   ❌ Azure DevOps project cannot be emptyz2Azure DevOps Personal Access Token cannot be emptyu6   ❌ Azure DevOps Personal Access Token cannot be empty   application/jsonBasic :AcceptAuthorizationc                 S   s   t | pdd}| S )Nr+   zhtml.parser)r   Zget_text)textZsoupr(   r(   r)   
clean_htmlU   s    z6AzureClient.fetch_azure_work_items.<locals>.clean_htmlr   c                 S   s   g | ]}t |qS r(   )r"   )r.   xr(   r(   r)   r0   [   s     r   z/_apis/wit/workitems?ids=z&api-version=6.0T)criticalc                      s   t j ddS )N   headerstimeout)requestsr   r(   r>   r   r(   r)   make_azure_requestb   s    z>AzureClient.fetch_azure_work_items.<locals>.make_azure_requestvaluer/   fieldszSystem.TitlezNo Title FoundzSystem.DescriptionzNo Description Found)r/   titledescriptionu   ✅ Successfully fetched z work items in batchz"Failed to fetch work items batch: u   ❌ z - ids: z#Error processing work items batch: )work_item_idsr   r   r   )osgetenvsplitr   r   r   r   r   r   r    base64	b64encodeencodedecoderangejoinr   status_codejsonr   r"   append	Exceptionr   )r&   rG   resultsZ
CHUNK_SIZEr9   iZ	chunk_idsZ	ids_paramrB   responsebodyitemsZwiZwidrD   rE   rF   	error_msger(   rA   r)   fetch_azure_work_items,   s    : z"AzureClient.fetch_azure_work_items)project_namec              
   C   s   zb| j  d| j d| d}ddtd| j    d}tj||dd	}|	  |
 W S  tk
r } ztd
| d|  W Y dS d}~X Y nX dS )zGet project informationr   z/_apis/projects/?api-version=6.0r2   r3   r4   r5   r<   r=   u   ❌ Failed to get project : N)r   r   rK   rL   r   rM   rN   r@   r   raise_for_statusrR   rT   r   )r&   r]   r   r>   rW   r[   r(   r(   r)   get_project   s    
zAzureClient.get_project)r]   limitc              
   C   s:  zt d|  | j d| j d| d}dddtd| j    d}d| d	g}|rt|t	t
frt|d
krddd |D }|d| d d|}d| d}	d|	i}
t d|  tj|||
dd}t d|j  |jdkrt d|j d|j  g W S |  | }|dg }t dt| d g }|dkr`|n
|d| }|D ]p}|d }| j d| j d| d | d!}tj||dd"}|jdkr||  nt d#| d$|j  qpt d%t| d& |W S  tk
r4 } zt d'|  g  W Y S d}~X Y nX dS )(a4  Get recent work items for suggestions
        :param project_name: Azure DevOps project name
        :param limit: Max number of items to return (None for all, details fetch still respects this cap)
        :param states: Optional list of state names to filter by (e.g., ['Ready for QA', 'Re-open'])
        u&   🔍 Fetching work items for project: r   z/_apis/wit/wiql?api-version=6.0r2   r3   r4   )r6   zContent-Typer7   z[System.TeamProject] = ''r   z, c                 S   s   g | ]}d | d qS )rc   r(   )r.   sr(   r(   r)   r0      s     z5AzureClient.get_recent_work_items.<locals>.<listcomp>z[System.State] IN ()z AND z_SELECT [System.Id], [System.Title], [System.WorkItemType], [System.State] FROM WorkItems WHERE z# ORDER BY [System.ChangedDate] DESCqueryu   🔍 Making WIQL request to: r<   )r>   rR   r?   u   🔍 WIQL response status: r1   u   ❌ WIQL request failed: z - Z	workItemsu   🔍 Found z work items in WIQL responseNr/   z/_apis/wit/workitems/r^   r=   u(   ❌ Failed to get details for work item r_   u&   🔍 Successfully fetched details for z work itemsu%   ❌ Failed to get recent work items: )r   r   r   rK   rL   r   rM   rN   r!   listtupler   rP   rS   r@   postrQ   r8   r`   rR   r   rT   )r&   r]   rb   statesr   r>   Zwhere_clausesZquoted_statesZ	where_sqlZ
wiql_querypayloadrW   result
work_itemsZdetailed_itemsZitems_to_processitemitem_idZitem_urlZitem_responser[   r(   r(   r)   get_recent_work_items   sN    

 z!AzureClient.get_recent_work_items)NNNN)N)NN)
__name__
__module____qualname__r*   r   r\   r"   ra   intrp   r(   r(   r(   r)   r      s
   
 Yr   )utils.error_loggerr   r   r   r   utils.error_monitorr   r   rH   r@   rK   Zbs4r   config.settingsr	   r
   r   r   r   r(   r(   r(   r)   <module>   s   