
    Ki(                        d Z ddlmZ ddlZddlZddl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mZmZ  ej&                  e      ZddZddZ	 d	 	 	 	 	 	 	 ddZddZy)zWiki generation from community structure.

Generates markdown pages for each detected community and an index page,
providing a navigable documentation wiki for the codebase architecture.
    )annotationsN)Counter)Path)Any   )get_communities)	get_flows)
GraphStore_sanitize_namec                |    t        j                  dd| j                               j                  d      }|dd xs dS )z1Convert a community name to a safe filename slug.z
[^a-z0-9]+-NP   unnamed)resublowerstrip)nameslugs     b/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/code_review_graph/wiki.py_slugifyr      s6    66-djjl399#>D9!	!    c                   |d   }|d   }|j                  dd      }|j                  dd      }|j                  dd      }g }|j                  d|        |j                  d       |j                  d	       |j                  d       |r#|j                  |        |j                  d       |j                  d
| d       |j                  d|d       |r|j                  d|        |j                  d       |j                  dg       }|j                  d       |j                  d       |r)|j                  d       |j                  d       d}	|dd D ]  }
| j                  |
      }|s|j                  dk7  s't	        |j
                        }|j                  d| d|j                   d|j                   d|j                   d|j                   d       |	dz  }	 |	s1|j                          |j                          |j                  d       t        |      dkD  rD|j                  d       |j                  dt        |      dz
   d       n|j                  d       |j                  d       |j                  d        |j                  d       t        |      }	 t        | d!d"#      }g }|D ]-  }| j                  |d$         }||z  s|j                  |       / |r|dd% D ]]  }t	        |j                  dd&            }|j                  d!d      }|j                  d'd      }|j                  d(| d)|d*d+| d,       _ t        |      d%kD  r3|j                  d-t        |      d%z
   d.       n|j                  d/       |j                  d       |j                  d2       |j                  d       	 t%               }t%               }|r[t'        |      }| j)                  |      D ]  }||vs||xx   dz  cc<    | j+                  |      D ]  }||vs||xx   dz  cc<    |rm|j                  d3       |j                  d       |j-                  d4      D ]&  \  }}|j                  d5t	        |       d6| d7       ( |j                  d       |rm|j                  d8       |j                  d       |j-                  d4      D ]&  \  }}|j                  d5t	        |       d6| d7       ( |j                  d       |s$|s"|j                  d9       |j                  d       d<j/                  |      S # t        j                  $ r2}t         j#                  d0|       |j                  d1       Y d}~d}~ww xY w# t        j                  $ rB}t         j#                  d:|       |j                  d;       |j                  d       Y d}~d}~ww xY w)=ah  Build markdown content for a single community.

    Includes: heading, overview (size, cohesion, language), members table
    (top 50), execution flows through the community, and dependencies.

    Args:
        store: The graph store.
        community: Community dict from get_communities().

    Returns:
        Markdown string for the community page.
    r   sizecohesiong        dominant_language descriptionz# z## Overviewz- **Size**: z nodesz- **Cohesion**: z.4fz- **Dominant Language**: membersz
## Membersz| Name | Kind | File | Lines |z|------|------|------|-------|r   N2   File|  | r   z |r   zNo non-file members found.z	*... and z more members.*zNo members found.z## Execution Flowscriticality   )sort_bylimitid
   r   depthz- **z** (criticality: z.2fz	, depth: )z- *... and z more flows.*z/No execution flows pass through this community.z!wiki: flows table unavailable: %sz"Execution flow data not available.z## Dependenciesz### Outgoing   z- `z` (z	 edge(s))z### Incomingz)No cross-community dependencies detected.z&wiki: dependency edges unavailable: %szDependency data not available.
)getappendget_nodekindr   r   	file_path
line_startline_endpoplensetr	   get_flow_qualified_namessqlite3OperationalErrorloggerdebugr   listget_outgoing_targetsget_incoming_sourcesmost_commonjoin)store	communityr   r   r   langr   lines
member_qnsmember_countqnnode	node_name
member_set	all_flowscommunity_flowsflowflow_qns	flow_namer$   r*   excoutgoing_targetsincoming_sourcesqnststargetcountsources                                 r   _generate_community_pagerZ      s    VDVD}}Z-H==,b1D--r2KE	LL2dV	LL 
LL	LL}&R	LL<vV,-	LL#HS>23078	LL y"-J	LL	LL5656 Sb/ 	"B>>"%D		V+*4995	3tyykT^^4D E)4==/= !	" IIKIIKLL56z?RLLLL9S_r%9$:/JK()	LL 
LL%&	LLZJ;e]#F	&( 	-D55d4jAH*$&&t,		- ', *488FI+FG	"hh}c:!,9+%6{36GyQVPWWXY	 ?#b({3+?"+D*E]STLLJK 
LL 
LL"#	LL$)0)0z"C //4 -J&$Q'1,'-
 //4 -J&$Q'1,'- LL(LL!1!=!=b!A Ps>&#9":#eWINOPLLLL(LL!1!=!=b!A Ps>&#9":#eWINOPLL(8LLDELL 99U] ## ;8#>9::;R ## =sC56RsD   0.U B;U 9V 'V 0DV V''VVW1/8W,,W1c                4   t        |      }|j                  dd       t        |       }d}d}d}g }t               }	|D ]  }
|
d   }t	        |      }|}d}||	v r| d| }|dz  }||	v r|	j                  |       | d}||z  }t        | |
      }|j                         r6|s4|j                  d	
      }||k(  r|dz  }|j                  |||
d   f       |j                         }|j                  |d	
       |r|dz  }n|dz  }|j                  |||
d   f        g }|j                  d       |j                  d       |j                  d       |j                  d       |j                  dt        |              |j                  d       |j                  d       |j                  d       |j                  d       |j                  d       t        |d       D ]$  \  }}}|j                  d| d| d| d| d	       & |j                  d       dj                  |      }|dz  }|j                         r8|s6|j                  d	
      }||k(  r|dz  }n1|j                  |d	
       |dz  }n|j                  |d	
       |dz  }|||dS )a  Generate a markdown wiki from the community structure.

    For each community, generates a markdown page. Also generates an
    index.md with links to all community pages.

    Args:
        store: The graph store.
        wiki_dir: Directory to write wiki pages into.
        force: If True, regenerate all pages even if content unchanged.

    Returns:
        Dict with pages_generated, pages_updated, pages_unchanged counts.
    T)parentsexist_okr   r      r   r   .mdutf-8encodingr   z# Code Wikir   zOAuto-generated documentation from the code knowledge graph community structure.z**Total communities**: z## Communitiesz| Community | Size | Link |z|-----------|------|------|c                    | d   S )Nr    )xs    r   <lambda>zgenerate_wiki.<locals>.<lambda>   s
    qt r   )keyr"   r#   z | [z.md](z.md) |r-   zindex.md)pages_generatedpages_updatedpages_unchanged)r   mkdirr   r7   r   addrZ   exists	read_textr/   
write_textr6   sortedrA   )rB   wiki_dirforce	wiki_pathcommunitiesrh   ri   rj   page_entries
used_slugscommr   	base_slugr   suffixfilenamefilepathcontentexistingalready_existedindex_linesr   index_content
index_pathexisting_indexs                            r   generate_wikir      s   $ XIOOD4O0!%(KOMO/1L 5J 8F|TN	j [&*DaKF j  	tV3<x'*5$7??U))7);H7"1$##T4f$>?"//+Gg6QMq OT4f6798>  K}%rY r0[1A0BCDr'(r4545"<^D LdDRvSd4&dV6JKLrIIk*MZ'J5#--w-?]*q O!!-'!BQMmg>1 +&* r   c                   t        |       }t        |      }|| dz  }|j                         r|j                  d      S ||z  j	                         }|j                         r1|j                  |j	                               r|j                  d      S |j                         rG|j                         D ]4  }|j                  dk(  s||j                  v s"|j                  d      c S  y)a  Retrieve a specific wiki page by community name.

    Args:
        wiki_dir: Directory containing wiki pages.
        page_name: Community name (will be slugified for filename lookup).

    Returns:
        Page content as a string, or None if the page does not exist.
    r_   r`   ra   N)
r   r   is_filern   resolveis_relative_tois_diriterdirry   stem)rq   	page_namers   r   r{   
exact_pathps          r   get_wiki_pager     s     XIIDdV3<'H!!7!33 i'002J
 9 9):K:K:M N##W#55 ""$ 	5Axx5 TQVV^{{G{44	5 r   )r   strreturnr   )rB   r
   rC   dict[str, Any]r   r   )F)rB   r
   rq   
str | Pathrr   boolr   r   )rq   r   r   r   r   z
str | None)__doc__
__future__r   loggingr   r9   collectionsr   pathlibr   typingr   rt   r   flowsr	   graphr
   r   	getLogger__name__r;   r   rZ   r   r   rd   r   r   <module>r      s    #  	     (  -			8	$"Kb ggg g 	gTr   