
    Rǻi0,                        d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZ ddlmZmZ e	 	 	 	 	 	 	 	 dded	ed   d
ededee	   dedededefd       Ze	 	 	 	 	 	 	 	 dded	ed   d
ededee	   dedededeee
eeeeef      f   f   fd       Z	 	 	 	 	 	 	 	 dded	ed
ededee	   dedededeee
eeeeef      f   f   fdZ	 	 	 dded
edededeee
eeeeef      f   ef   f
dZ	 	 	 dde	d
edededeee
eeeeef      f   f   f
dZ	 	 	 dded
edededeee
eeeeef      f   f   f
dZd deee      defdZedk(  r ej2                   e              yy)!a%  
This module will parse the JSON file following the BNF definition:

    <json> ::= <container>

    <primitive> ::= <number> | <string> | <boolean>
    ; Where:
    ; <number> is a valid real number expressed in one of a number of given formats
    ; <string> is a string of valid characters enclosed in quotes
    ; <boolean> is one of the literal strings 'true', 'false', or 'null' (unquoted)

    <container> ::= <object> | <array>
    <array> ::= '[' [ <json> *(', ' <json>) ] ']' ; A sequence of JSON values separated by commas
    <object> ::= '{' [ <member> *(', ' <member>) ] '}' ; A sequence of 'members'
    <member> ::= <string> ': ' <json> ; A pair consisting of a name, and a JSON value

If something is wrong (a missing parantheses or quotes for example) it will use a few simple heuristics to fix the JSON string:
- Add the missing parentheses if the parser believes that the array or object should be closed
- Quote strings or add missing single quotes
- Adjust whitespaces and remove line breaks

All supported use cases are in the unit tests
    N)DictListLiteralOptionalTextIOTupleUnionoverload   )
JSONParserJSONReturnTypeFTjson_strreturn_objectsskip_json_loadsloggingjson_fdensure_asciichunk_lengthstream_stablereturnc                      y N r   r   r   r   r   r   r   r   s           U/opt/lhia/marcimex/agent/venv/lib/python3.12/site-packages/json_repair/json_repair.pyrepair_jsonr   !   s         c                      y r   r   r   s           r   r   r   .   s	     JMr   c                 .   t        | ||||      }|r|j                         }	n.	 |rt        j                  |      }	nt        j                  |       }	|s|r|	S t        j                  |	|      S # t        j
                  $ r |j                         }	Y Bw xY w)a  
    Given a json formatted string, it will try to decode it and, if it fails, it will try to fix it.

    Args:
        json_str (str, optional): The JSON string to repair. Defaults to an empty string.
        return_objects (bool, optional): If True, return the decoded data structure. Defaults to False.
        skip_json_loads (bool, optional): If True, skip calling the built-in json.loads() function to verify that the json is valid before attempting to repair. Defaults to False.
        logging (bool, optional): If True, return a tuple with the repaired json and a log of all repair actions. Defaults to False.
        json_fd (Optional[TextIO], optional): File descriptor for JSON input. Do not use! Use `from_file` or `load` instead. Defaults to None.
        ensure_ascii (bool, optional): Set to False to avoid converting non-latin characters to ascii (for example when using chinese characters). Defaults to True. Ignored if `skip_json_loads` is True.
        chunk_length (int, optional): Size in bytes of the file chunks to read at once. Ignored if `json_fd` is None. Do not use! Use `from_file` or `load` instead. Defaults to 1MB.
        stream_stable (bool, optional): When the json to be repaired is the accumulation of streaming json at a certain moment.If this parameter to True will keep the repair results stable.
    Returns:
        Union[JSONReturnType, Tuple[JSONReturnType, List[Dict[str, str]]]]: The repaired JSON or a tuple with the repaired JSON and repair log.
    )r   )r   parsejsonloadloadsJSONDecodeErrordumps)
r   r   r   r   r   r   r   r   parserparsed_jsons
             r   r   r   ;   s    2 '7L-PFlln	)"ii0"jj2
 ::k== ## 	) ,,.K	)s   -A. .#BBc                 "    t        | d|||      S )a  
    This function works like `json.loads()` except that it will fix your JSON in the process.
    It is a wrapper around the `repair_json()` function with `return_objects=True`.

    Args:
        json_str (str): The JSON string to load and repair.
        skip_json_loads (bool, optional): If True, skip calling the built-in json.loads() function to verify that the json is valid before attempting to repair. Defaults to False.
        logging (bool, optional): If True, return a tuple with the repaired json and a log of all repair actions. Defaults to False.

    Returns:
        Union[JSONReturnType, Tuple[JSONReturnType, List[Dict[str, str]]], str]: The repaired JSON object or a tuple with the repaired JSON object and repair log.
    T)r   r   r   r   r   r   )r   r   r   r   s       r   r#   r#   f   s     $ '# r   fdc                 "    t        | |d||      S )aU  
    This function works like `json.load()` except that it will fix your JSON in the process.
    It is a wrapper around the `repair_json()` function with `json_fd=fd` and `return_objects=True`.

    Args:
        fd (TextIO): File descriptor for JSON input.
        skip_json_loads (bool, optional): If True, skip calling the built-in json.loads() function to verify that the json is valid before attempting to repair. Defaults to False.
        logging (bool, optional): If True, return a tuple with the repaired json and a log of all repair actions. Defaults to False.
        chunk_length (int, optional): Size in bytes of the file chunks to read at once. Defaults to 1MB.

    Returns:
        Union[JSONReturnType, Tuple[JSONReturnType, List[Dict[str, str]]]]: The repaired JSON object or a tuple with the repaired JSON object and repair log.
    T)r   r   r   r   r   r)   r*   r   r   r   s       r   r"   r"      s     & !' r   filenamec                 f    t        |       5 }t        ||||      }ddd       |S # 1 sw Y   S xY w)a
  
    This function is a wrapper around `load()` so you can pass the filename as string

    Args:
        filename (str): The name of the file containing JSON data to load and repair.
        skip_json_loads (bool, optional): If True, skip calling the built-in json.loads() function to verify that the json is valid before attempting to repair. Defaults to False.
        logging (bool, optional): If True, return a tuple with the repaired json and a log of all repair actions. Defaults to False.
        chunk_length (int, optional): Size in bytes of the file chunks to read at once. Defaults to 1MB.

    Returns:
        Union[JSONReturnType, Tuple[JSONReturnType, List[Dict[str, str]]]]: The repaired JSON object or a tuple with the repaired JSON object and repair log.
    r,   N)openr"   )r-   r   r   r   r*   jsonobjs         r   	from_filer1      sA    $ 
h 
2+%	

 N
 Ns   &0inline_argsc                    t        j                  d      }|j                  ddd       |j                  ddd	d
       |j                  dddd       |j                  dd	d       |j                  dt        dd       | |j	                         }n|j	                  |       }|j
                  r<|j                  s0t        dt        j                         t        j                  d       |j
                  r<|j                  r0t        dt        j                         t        j                  d       d}|j                  rd}	 |j                  rt        |j                        }n)t        j                  j                         }t!        |      }|j
                  s|j                  rRt#        |j                  xs |j                  d      5 }t%        j&                  |||j(                  |        ddd       y"t        t%        j*                  ||j(                  |              	 y"# 1 sw Y   y"xY w# t,        $ r(}t        d!|t        j                         Y d}~yd}~ww xY w)#a  
    Command-line interface for repairing and parsing JSON files.

    Args:
        inline_args (Optional[List[str]]): List of command-line arguments for testing purposes. Defaults to None.
            - filename (str): The JSON file to repair. If omitted, the JSON is read from stdin.
            - -i, --inline (bool): Replace the file inline instead of returning the output to stdout.
            - -o, --output TARGET (str): If specified, the output will be written to TARGET filename instead of stdout.
            - --ensure_ascii (bool): Pass ensure_ascii=True to json.dumps(). Will pass False otherwise.
            - --indent INDENT (int): Number of spaces for indentation (Default 2).

    Returns:
        int: Exit code of the CLI operation.

    Raises:
        Exception: Any exception that occurs during file processing.

    Example:
        >>> cli(['example.json', '--indent', '4'])
        >>> cat json.txt | json_repair
    zRepair and parse JSON files.)descriptionr-   ?z6The JSON file to repair (if omitted, reads from stdin))nargshelpz-iz--inline
store_truezAReplace the file inline instead of returning the output to stdout)actionr7   z-oz--outputTARGETzMIf specified, the output will be written to TARGET filename instead of stdout)metavarr7   z--ensure_asciiz&Pass ensure_ascii=True to json.dumps()z--indent   z,Number of spaces for indentation (Default 2))typedefaultr7   Nz&Error: Inline mode requires a filename)filer   z1Error: You cannot pass both --inline and --outputFTw)mode)indentr   zError: r   )argparseArgumentParseradd_argumentint
parse_argsinliner-   printsysstderrexitoutputr   r1   stdinreadr#   r/   r!   dumprB   r%   	Exception)r2   r&   argsr   resultdatar*   es           r   clirV      s   , $$1OPF
E  
 P	   \	   5  
 ;	     "  - {{4==6SZZH{{t{{A

SL==t}}-F99>>#D4[F;;$++dkk2T]]= U		&"T[[|TU  $**VDKKlST
 U 	  uoCJJ/s=   BH5 $H)3H5 <+H5 )H2.H5 2H5 5	I&>I!!I&__main__) FFFNTr   F)rX   TFFNTr   F)FFF)FFr   r   )__doc__rC   r!   rJ   typingr   r   r   r   r   r   r	   r
   json_parserr   r   strboolrF   r   r#   r"   r1   rV   __name__rL   r   r   r   <module>r_      s\  0   
 P P P 3 
%*! $		EN	 	 		
 f	 	 	 	 		 
	 
$(! $	M	MDM	M 	M 		M
 f	M 	M 	M 	M >5d38n1E!EFFG	M 
	M  ! $(>(>(> (> 	(>
 f(> (> (> (> >5d38n1E!EFFG(>Z "	  	
 >5d38n1E!EFKL: "	  	
 >5d38n1E!EFFG< "	  	
 >5d38n1E!EFFG:WXd3i( WC Wt zCHHSUO r   