
    lKjk^                        d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZmZ erddlmZ ddlmZ dd	d
edefdZdeeedf   ef   defdZdedefdZdedefdZd
edeeedf   ef   dee   fdZd
edeeedf   ef   dee   fdZdedefdZdeeedf   ef   d
edeedf   deedf   dee   f
dZdeeedf   ef   deedf   d
edeedf   deedf   dee   fdZdedeedf   d
edee   fdZdedeedf   d
ededee   f
dZ deedf   dee   fd Z!d
ededeedf   deedf   dee   f
d!Z"d"ed
eded#edee   f
d$Z#d%ed
eded#edee   f
d&Z$deedf   d
edefd'Z%d(d)d#edefd*Z&y)+zFish completion script generator.

Generates static fish completion scripts using `complete -c COMMAND` statements.
Completions auto-load from ~/.config/fish/completions/PROGNAME.fish.
    N)TYPE_CHECKING)is_iterable_type)CompletionActionCompletionDataclean_choice_textextract_completion_dataget_completion_actionstrip_markup)App)CommandSpecappr   	prog_namereturnc                 n   |rt        j                  d|      st        d|d      t        |       }d| ddg}t	        d |j                         D              }|r,|j                  t        ||             |j                  d       t        |      r,|j                  t        ||             |j                  d       | j                  rt        | j                        nd}| j                  rt        | j                        nd}|j                  t        ||||             d	j                  |      d	z   S )
a  Generate fish completion script.

    Parameters
    ----------
    app : App
        The Cyclopts application to generate completion for.
    prog_name : str
        Program name for completion (alphanumeric with hyphens/underscores).

    Returns
    -------
    str
        Complete fish completion script.

    Raises
    ------
    ValueError
        If prog_name contains invalid characters.
    z^[a-zA-Z0-9_-]+$zInvalid prog_name: z0. Must be alphanumeric with hyphens/underscores.z# Fish completion for z# Generated by Cyclopts c              3   8   K   | ]  }t        |      d kD    yw)r   N)len).0paths     i/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/cyclopts/completion/fish.py	<genexpr>z-generate_completion_script.<locals>.<genexpr>8   s     O8Nc$i!m8Ns    
)rematch
ValueErrorr   anykeysextend_generate_helper_functionsappend_any_nested_positional_choices!_generate_positional_index_helper
help_flagstupleversion_flags_generate_completionsjoin)r   r   completion_datalineshas_nested_commandsr$   r&   s          r   generate_completion_scriptr,      s   ( BHH%8)D.ym;klmm-c2O !,!
E O8L8L8NOO/	?KLR%o66y/RSR*-..s~~&bJ030A0AE#++,rM	LL&	:}]^99Ud""    r)   .c                     | j                         D ]G  \  }}|s	|j                  D ]0  }|j                  |j                  s|j	                  d      s/  y I y)u#  Whether any nested command path has a positional argument with choices.

    The positional-index helper is only needed when there is at least one
    nested positional that emits a choice list — without choices, fish's
    default file fallback already produces sensible completions.
    TforceF)items	argumentsindexshowget_choices)r)   r   dataarguments       r   r"   r"   I   s[     &++-
dH~~%X]]##$#/	 ' . r-   textc                 &    | j                  dd      S )z&Escape single quotes for fish strings.'z'\'')replacer8   s    r   _escape_fish_stringr=   [   s    <<W%%r-   c                 `    | j                  dd      } | j                  dd      } t        |       S )z!Escape description text for fish.r    )r;   r=   r<   s    r   _escape_fish_descriptionrA   `   s-    <<c"D<<c"Dt$$r-   c                 <   t               }t               }|j                         D ]  }|j                  D ]h  }|j                         r|j                  j
                  s+|j                  j
                  D ]%  }|j                  d      s|j                  |       ' j |j                  D ]6  }|j                  D ]%  }|j                  d      r|j                  |       ' 8  d|  d}	dd|	 ddg}
|r7dj                  d	 t        |      D              }|
j                  d
| d       n|
j                  d       |r7dj                  d t        |      D              }|
j                  d| d       n|
j                  d       |
j                  g d       |
S )uD  Generate helper function for command path detection.

    Non-option words are classified by membership in a globally-aggregated
    set of registered command names (``all_commands``) — this matches the
    bash detector's behavior and prevents positional argument *values* from
    being mistaken for subcommands. Without this filter, typing any
    positional after the subcommand causes the helper to count it as a
    deeper command path, which then makes every ``-n '<helper> <path>'``
    rule (including option and positional-choice rules) stop firing.

    Note: ``all_commands`` is built globally across all command levels —
    a positional value that happens to equal a real subcommand name from
    *some* level can still be misclassified, but that represents poor CLI
    design and matches the bash detector's behavior.

    Parameters
    ----------
    prog_name : str
        Program name.
    completion_data : dict
        Completion data used to identify options that take values.

    Returns
    -------
    list[str]
        Lines defining the helper function.
    -__fish__using_commandz6# Helper function to check exact command path sequence	function !    set -l cmd (commandline -opc)z    set -l subcommandsr?   c              3   2   K   | ]  }t        |        y wNr=   r   opts     r   r   z-_generate_helper_functions.<locals>.<genexpr>        `D_S 3C 8D_        set -l options_with_values 'r:   !    set -l options_with_values ''c              3   2   K   | ]  }t        |        y wrI   rJ   r   cmds     r   r   z-_generate_helper_functions.<locals>.<genexpr>   s     YDXS 3C 8DXrN   z    set -l all_commands 'z    set -l all_commands '')    set -l skip_next 0zJ    # Extract command words (only real subcommand names) from command line!    for i in (seq 2 (count $cmd))        set -l word $cmd[$i]         if test $skip_next -eq 1            set skip_next 0            continue        end)        if string match -qr -- '^-' $wordz>            # Check if this option takes a value (exact match)F            if string match -q -- "* $word *" " $options_with_values "                set skip_next 1            end        elsezJ            # Only add to subcommands if word is a registered command namez?            if string match -q -- "* $word *" " $all_commands "z(                set -a subcommands $wordr^   rZ       endz8    # Check if subcommand sequence matches expected pathz2    if test (count $subcommands) -ne (count $argv)z        return 1r`   z"    for i in (seq 1 (count $argv))z-        if test $subcommands[$i] != $argv[$i]z            return 1rZ   r`   z    return 0end)setvaluesr2   is_flag	parametername
startswithaddcommandsnamesr(   sortedr!   r   )r   r)   options_with_valuesall_commandsr6   r7   rf   registered_commandcmd_name	func_namer*   escaped_optsescaped_cmdss                r   r    r    g   s   > %5L&&(H##%(*<*<*A*A$..33Ds++//5 4 '
 #'--.44**3/ $$X. 5 #0 ) )N3I@
I;+ 	E xx`FK^D_``7~QGH89xxYF<DXYY0a@A12	LL 	
"F Lr-   c                 
   t               }|j                         D ]y  }|j                  D ]h  }|j                         r|j                  j
                  s+|j                  j
                  D ]%  }|j                  d      s|j                  |       ' j { d|  d}dd| ddg}|r7dj                  d	 t        |      D              }|j                  d
| d       n|j                  d       |j                  g d       |S )u  Emit a fish function that returns the current positional slot index.

    The function takes one argument — the length of the active command path
    — and walks ``commandline -opc`` to count non-option, non-path tokens
    encountered before the cursor. Options that take a value are detected
    using a globally-aggregated list (same approach as the
    ``__fish_<prog>_using_command`` helper) so their value tokens don't get
    counted as positionals.
    rC   rD   _positional_indexzR# Helper: print the index of the next positional slot for the active command path.rF   rG   z    set -l path_len $argv[1]r?   c              3   2   K   | ]  }t        |        y wrI   rJ   rK   s     r   r   z4_generate_positional_index_helper.<locals>.<genexpr>   rM   rN   rO   r:   rP   )rT   z    set -l consumed_path 0z    set -l count 0rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   z0            if test $consumed_path -lt $path_lenz;                set consumed_path (math $consumed_path + 1)z            elsez+                set count (math $count + 1)r^   rZ   r`   z    echo $countra   )rb   rc   r2   rd   re   rf   rg   rh   r(   rk   r!   r   )	r   r)   rl   r6   r7   rf   rp   r*   rq   s	            r   r#   r#      s     %&&(H##%(*<*<*A*A$..33Ds++//5 4 ' ) )$56I\
I;+&	E xx`FK^D_``7~QGH89	LL	
6 Lr-   actionc                 T    | t         j                  k(  ry| t         j                  k(  ryy)a	  Map completion action to fish flags.

    Parameters
    ----------
    action : CompletionAction
        Completion action type.

    Returns
    -------
    str
        Fish completion flags ("-r -F" for files, "-r -a '(...)'" for directories, "" otherwise).
    z-r -Fz%-r -a '(__fish_complete_directories)'r   )r   FILESDIRECTORIES)rv   s    r   _map_completion_action_to_fishrz     s+     !'''!---6r-   r$   r&   c           
          g }t        | j                               D ]W  \  }}|j                  t        | ||||             |t	        | j                         t              k7  sG|j                  d       Y |S )ak  Generate all fish completion commands.

    Parameters
    ----------
    completion_data : dict
        Extracted completion data.
    prog_name : str
        Program name.
    help_flags : tuple[str, ...]
        Help flags.
    version_flags : tuple[str, ...]
        Version flags.

    Returns
    -------
    list[str]
        Completion command lines.
    keyr   )rk   r1   r   _generate_completions_for_pathmaxr   r   r!   )r)   r   r$   r&   r*   command_path_datas          r   r'   r'   !  sv    0 E%o&;&;&=>e*	
 33353??LL  ? Lr-   r   c                 L   || vrg S | |   }g }t        ||      }|j                  t        ||||             |j                  D cg c]"  }|j	                         r|j
                  s!|$ }	}|	s|s|r|j                  t        |             |j                  t        ||||             |j                  t        |	|||j                               |j                  t        |j                  |||j                               |j                  t        |||             |S c c}w )a  Generate completions for a specific command path.

    Parameters
    ----------
    completion_data : dict
        Extracted completion data.
    command_path : tuple[str, ...]
        Command path.
    prog_name : str
        Program name.
    help_flags : tuple[str, ...]
        Help flags.
    version_flags : tuple[str, ...]
        Version flags.

    Returns
    -------
    list[str]
        Completion command lines.
    )_get_condition_for_pathr    _generate_subcommand_completionsr2   is_positional_onlyr4   _generate_option_section_header"_generate_help_version_completions!_generate_keyword_arg_completionshelp_format$_generate_command_option_completionsri    _generate_positional_completions)
r)   r   r   r$   r&   r6   r*   	conditionargkeyword_argss
             r   r~   r~   K  s   6 ?*	<(DE'i@I	LL1$iQZ[\#'>>_>C9O9O9QVYV^V^C>L_z]4\BC7	9jZghi6|YPY[_[k[klm9$--T]_c_o_opq	LL1$iPQL `s   D!D!(D!r6   c           
      (   sg S | j                   D cg c]  }|j                  |j                  s|  }}|sg S |j                  d        d}t	        |      D ]  \  }}|j                         s|} n |,t	        |      D ]  \  }}t        |j                        s|} n ||n|d| }|dn||   }d| d}	d| d}
t              }dj                  d D              }|
 d| }g d	dfd
}t	        |      D ]{  \  }}|j                  d      }|s|D cg c]  }t        t        |             }}dj                  |      }| d|	 d| d| } |        j                  d| d| d| d       } |{|j                  d      }|rg||nd}|D cg c]  }t        t        |             }}dj                  |      }| d|	 d| d| } |        j                  d| d| d| d       S c c}w c c}w c c}w )u  Emit per-position choice rules for positional args at a nested path.

    Only nested paths (``len(command_path) > 0``) are handled. At root, the
    natural fish gate ``__fish_use_subcommand`` flips false as soon as the
    first positional is typed, so a position-N rule for N>0 can't be
    expressed cleanly there; root-level positional values (rare in practice)
    fall back to fish's default behavior.

    Positionals without choices (e.g. ``Path``) emit nothing — fish's
    default file completion kicks in automatically at positions where no
    rule fires.

    Iterable positionals (``list[X]``, ``set[X]``, ``*args``) own every
    slot from their index onwards. To avoid emitting two competing
    rest-arg specs (mirrors the bash/zsh "first iterable wins" rule), only
    the first iterable contributes a rest rule; later iterables remain
    reachable via their ``--name`` keyword forms.
    Nc                 "    | j                   xs dS )Nr   )r3   )as    r   <lambda>z2_generate_positional_completions.<locals>.<lambda>  s    qww|!|r-   r|   rD   rt   rE   r?   c              3   2   K   | ]  }t        |        y wrI   rJ   rR   s     r   r   z3_generate_positional_completions.<locals>.<genexpr>       QLS 3C 8LrN   Fc                  V    s&j                  ddj                                 dy y )Nz# Positionals for: r?   T)r!   r(   )r   header_emittedr*   s   r   _ensure_headerz8_generate_positional_completions.<locals>._ensure_header  s.    LL.sxx/E.FGH!N r-   Tr/   z; and test (z) = complete -c z -n 'z	' -f -a 'r:   r   z) -ge )r   N)r2   r3   r4   sort	enumerateis_var_positionalr   hintr   r(   r5   r=   r   r!   )r6   r   r   r   positional_argsrest_idxihead
rest_owner	helper_fnusing_cmd_fnpath_lenescaped_commandsbase_predicater   slot_idxr7   choicescescaped_choiceschoices_strpos_cond	rest_slotr   r*   s    `                     @@r   r   r   {  s   . 	&*nn[ns		8MRURZRZsnO[	34HO,3  "H - 0FAs) 1
 '.?OIX4ND!)x/HJ)$56IYK~6L< HxxQLQQ$~Q'7&89NEN" (o(&&T&2NUVg./@/CDgVhh/$%\)AhZtH:V|I;eH:Y{mSTUV . ((t(4$,$8aIRYZRYQ23DQ3GHRYOZ((?3K()i[(6R[Q\]HLL<	{%z;-WXYZLo \N W [s   HHH'H
&Hr   c                    | j                   D cg c]'  }|j                  D ]  }|j                  d      r| ) }}}|sg S g }|r$|j                  ddj	                  |              n|j                  d       | j                   D ]y  }|j                  D ]h  }|j                  d      rt        |j                  | j                        }	t        |	      }
t        |      }|j                  d| d| d| d|
 d	       j { |S c c}}w )	aT  Generate completions for subcommands.

    Parameters
    ----------
    data : CompletionData
        Completion data.
    command_path : tuple[str, ...]
        Command path.
    prog_name : str
        Program name.
    condition : str
        Fish condition.

    Returns
    -------
    list[str]
        Completion command lines.
    rC   z# Subcommands for: r?   z# Root-level commandsr   z -a '' -d 'r:   )
ri   rj   rg   r!   r(   _get_description_from_appr   r   rA   r=   )r6   r   r   r   rn   rf   ri   r*   ro   descescaped_descescaped_cmds               r   r   r     s   2 (,}}'4#ASAYAYaeapapqtauAY}   	E*388L+A*BCD,-"mm*00H""3',-?-C-CTEUEUVD3D9L-h7KLL<	{!I;eK=PVWcVddefg 1 , L/s
   %DDc                 6    | rddj                  |        gS dgS )zGenerate section header comment for options.

    Parameters
    ----------
    command_path : tuple[str, ...]
        Command path.

    Returns
    -------
    list[str]
        Comment line.
    z# Options for: r?   z# Root-level optionsr(   )r   s    r   r   r     s*     !#((<"8!9:;;"##r-   c           
         g }|D ]u  }|j                  d      r!|dd }|j                  d|  d| d| d       5|j                  d      sGt        |      dk(  sV|d	   }|j                  d|  d| d
| d       w |D ]u  }|j                  d      r!|dd }|j                  d|  d| d| d       5|j                  d      sGt        |      dk(  sV|d	   }|j                  d|  d| d
| d       w |S )ac  Generate completions for help and version flags.

    Parameters
    ----------
    prog_name : str
        Program name.
    condition : str
        Fish condition.
    help_flags : tuple[str, ...]
        Help flags.
    version_flags : tuple[str, ...]
        Version flags.

    Returns
    -------
    list[str]
        Completion command lines.
    --   Nr   r?    -l z$ -d 'Display this message and exit.'rC       -s z" -d 'Display application version.')rg   r!   r   )r   r   r$   r&   r*   flag	long_name
short_names           r   r   r     s   0 E??4 QRILL<	{!I;d9+Mqrs__S!c$i1naJLL<	{!I;d:,Nrst  ??4 QRILL<	{!I;d9+Mopq__S!c$i1naJLL<	{!I;d:,Npqr  Lr-   r   r   c                 t   g }| D ]*  }t        |j                  j                  xs d|      }t        |      }|j	                         }|j                  d      }	t        |j                        }
|j                  j                  xs g D ]  }|j                  d      s|j                  d      r|dd }d	| d
| d| g}n!t        |      dk(  r|d   }d	| d
| d| g}nZ|r|j                  d| d       n|	rK|	D cg c]  }t        t        |             }}d
j                  |      }|j                  d| d| d       n:t        |
      }|r|j                  | d| d       n|j                  d| d       |j                  d
j                  |              |j                   D ]{  }|j                  d      s|j                  d      r$|dd }|j                  d	| d
| d| d| d	       Jt        |      dk(  sY|d   }|j                  d	| d
| d| d| d	       } - |S c c}w )aQ  Generate completions for keyword arguments.

    Parameters
    ----------
    keyword_args : list
        Keyword arguments.
    prog_name : str
        Program name.
    condition : str
        Fish condition.
    help_format : str
        Help text format.

    Returns
    -------
    list[str]
        Completion command lines.
    r   formatTr/   rC   r   r   Nr   r?   r   r   r   z-d 'r:   z-x -a 'r    -d 'z-r -d ')r
   re   helprA   rd   r5   r	   r   rf   rg   r   r!   r=   r   r(   rz   	negatives)r   r   r   r   r*   r7   r   r   rd   r   rv   rf   r   
line_partsr   r   r   r   action_flagss                      r   r   r   @  sj   0 E H..339r+N/5""$&&T&2&x}}5&&++1r1D??3't$ H	 ,YKq4	{ST
Ta!!W
 ,YKq4
|TU
!!Da"89V]"^V]QR#67H7K#LV]"^!hh7!!GK=|nA"NO=fE%%eL>&KL%%~Q&?@LL*-.5 28 &&D??3't$ H	|I;a	{$ykQVWcVddefgTa!!W
|I;a	{$zlRWXdWeefgh 'I !^ L/ #_s   H5ri   c                 n   g }| D ]  }|j                   D ]  }|j                  d      st        |j                  |      }t	        |      }|j                  d      r$|dd }	|j                  d| d| d|	 d| d		       kt        |      dk(  sz|d
   }
|j                  d| d| d|
 d| d		         |S )aj  Generate completions for commands that look like options.

    Parameters
    ----------
    commands : list
        List of RegisteredCommand tuples.
    prog_name : str
        Program name.
    condition : str
        Fish condition.
    help_format : str
        Help text format.

    Returns
    -------
    list[str]
        Completion command lines.
    rC   r   r   Nr   r?   r   r   r:   r   r   )rj   rg   r   r   rA   r!   r   )ri   r   r   r   r*   rn   ro   r   r   r   r   s              r   r   r     s    0 E&*00H&&s+,-?-C-C[QD3D9L""4($QRL	|I;a	{$ykQVWcVddefgX!#%a[
|I;a	{$zlRWXdWeefgh 1 ' Lr-   c                 V    | syd| d}dj                  d | D              }d| d| dS )a  Generate fish condition string for a command path.

    Parameters
    ----------
    command_path : tuple[str, ...]
        Command path (empty for root).
    prog_name : str
        Program name.

    Returns
    -------
    str
        Fish condition flag.
    z-n __fish_use_subcommandrD   rE   r?   c              3   2   K   | ]  }t        |        y wrI   rJ   rR   s     r   r   z*_get_condition_for_path.<locals>.<genexpr>  r   rN   z-n 'r:   r   )r   r   rp   r   s       r   r   r     sD     ))N3IxxQLQQ)A./q11r-   cmd_appzApp | CommandSpecc                     ddl m} 	  || j                  d      }|j                  xs d}t        ||      S # t        $ r t        | j                  xs d      }Y 1w xY w)zExtract description from App.

    Parameters
    ----------
    cmd_app : App | CommandSpec
        Command app or spec.
    help_format : str
        Help text format.

    Returns
    -------
    str
        Description text.
    r   )docstring_parse	plaintextr   r   )cyclopts.help.helpr   r   short_description	Exceptionstrr
   )r   r   r   parsedr8   s        r   r   r     s_     3' {;''-2 [11  '7<<%2&'s   #8 "AA)'__doc__r   typingr   cyclopts.annotationsr   cyclopts.completion._baser   r   r   r   r	   r
   cycloptsr   cyclopts.command_specr   r   r,   dictr%   boolr"   r=   rA   listr    r#   rz   r'   r~   r   r   r   r   r   r   r   r   r   r-   r   <module>r      sq   
   1  1-#E -#c -#c -#`DsCx.9X4Y ^b $&c &c &
%3 %3 %cc%S/>9:c 
#YcL==%S/>9:= 
#Y=@+;  ('%S/>9:'' c3h' c?	'
 
#Y'T-%S/>9:-S/- - c3h	-
 c?- 
#Y-`Q
QS/Q Q 
#Y	Qh/
/S// / 	/
 
#Y/d$%S/ $d3i $$*** c3h* c?	*
 
#Y*ZIII I 	I
 
#YIX))) ) 	)
 
#Y)X2%S/ 2c 2c 2.2': 2 2QT 2r-   