/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

package org.elasticsearch.common.logging;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.message.SimpleMessage;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Pattern;

import static org.hamcrest.Matchers.equalTo;

public class JsonThrowablePatternConverterTests extends ESTestCase {
    private static final Pattern NEWLINE = Pattern.compile("\\R");
    private JsonThrowablePatternConverter converter = JsonThrowablePatternConverter.newInstance(null, null);

    public void testNoStacktrace() throws IOException {
        LogEvent event = Log4jLogEvent.newBuilder().build();
        String result = format(event);

        JsonLogLine jsonLogLine = JsonLogsStream.from(new BufferedReader(new StringReader(result)))
            .findFirst()
            .orElseThrow(() -> new AssertionError("no logs parsed"));

        assertThat(jsonLogLine.stacktrace(), Matchers.nullValue());
    }

    public void testStacktraceWithJson() throws IOException {
        String json = """
            {
              "terms": {
                "user": [
                  "u1",
                  "u2",
                  "u3"
                ],
                "boost": 1.0
              }
            }\
            """;
        Exception thrown = new Exception(json);
        LogEvent event = Log4jLogEvent.newBuilder().setMessage(new SimpleMessage("message")).setThrown(thrown).build();

        String result = format(event);

        // confirms exception is correctly parsed

        JsonLogLine jsonLogLine = JsonLogsStream.from(new BufferedReader(new StringReader(result)), JsonLogLine.ES_LOG_LINE)
            .findFirst()
            .orElseThrow(() -> new AssertionError("no logs parsed"));

        int jsonLength = NEWLINE.split(json).length;
        int stacktraceLength = thrown.getStackTrace().length;
        assertThat(
            "stacktrace should formatted in multiple lines. JsonLogLine= " + jsonLogLine + " result= " + result,
            jsonLogLine.stacktrace().size(),
            equalTo(jsonLength + stacktraceLength)
        );
    }

    private String format(LogEvent event) {
        StringBuilder builder = new StringBuilder();
        converter.format(event, builder);
        String jsonStacktraceElement = builder.toString();

        return """
            {
              "type": "console",
              "timestamp": "2019-01-03T16:30:53,058+0100",
              "level": "DEBUG",
              "component": "o.e.a.s.TransportSearchAction",
              "cluster.name": "clustername",
              "node.name": "node-0",
              "cluster.uuid": "OG5MkvOrR9azuClJhWvy6Q",
              "node.id": "VTShUqmcQG6SzeKY5nn7qA",
              "message": "msg msg"
              %s
            }""".formatted(jsonStacktraceElement);
    }
}

@@ -732,21 +732,25 @@
 til.
-regex.Pattern
+stream.Collectors
 ;%0A%0Ai
@@ -892,47 +892,53 @@
 nal 
-Pattern NEWLINE = Pattern.compile(%22%5C%5CR%22
+String LINE_SEPARATOR = System.lineSeparator(
 );%0A 
@@ -1792,16 +1792,68 @@
      %22%22%22
+.lines().collect(Collectors.joining(LINE_SEPARATOR))
 ;%0A      
@@ -2356,26 +2356,33 @@
 h = 
-NEWLINE.split(json
+json.split(LINE_SEPARATOR
 ).le
@@ -2915,55 +2915,28 @@
 rn %22
-%22%22%0A            %7B%0A              
+%7B%5C
 %22type
+%5C
 %22: 
+%5C
 %22console
 %22,%0A 
@@ -2931,33 +2931,21 @@
 %22console
+%5C
 %22,
-%0A             
  
+%5C
 %22timesta
@@ -2946,19 +2946,21 @@
 imestamp
+%5C
 %22: 
+%5C
 %222019-01
@@ -2984,42 +2984,35 @@
 0100
+%5C
 %22,
-%0A             
  
+%5C
 %22level
+%5C
 %22: 
+%5C
 %22DEBUG
+%5C
 %22,
+ %22
 %0A   
@@ -3020,18 +3020,20 @@
         
-  
++ %22%5C
 %22compone
@@ -3034,19 +3034,21 @@
 omponent
+%5C
 %22: 
+%5C
 %22o.e.a.s
@@ -3069,33 +3069,21 @@
 chAction
+%5C
 %22,
-%0A             
  
+%5C
 %22cluster
@@ -3087,19 +3087,21 @@
 ter.name
+%5C
 %22: 
+%5C
 %22cluster
@@ -3104,33 +3104,21 @@
 stername
+%5C
 %22,
-%0A             
  
+%5C
 %22node.na
@@ -3123,20 +3123,25 @@
 name
+%5C
 %22: 
+%5C
 %22node-0
+%5C
 %22,
+ %22
 %0A   
@@ -3149,18 +3149,20 @@
         
-  
++ %22%5C
 %22cluster
@@ -3166,19 +3166,21 @@
 ter.uuid
+%5C
 %22: 
+%5C
 %22OG5MkvO
@@ -3198,33 +3198,21 @@
 vy6Q
+%5C
 %22,
-%0A             
  
+%5C
 %22node.id
 %22: %22
@@ -3207,19 +3207,21 @@
 %22node.id
+%5C
 %22: 
+%5C
 %22VTShUqm
@@ -3239,33 +3239,22 @@
 n7qA
+%5C
 %22,
-%0A            
   
+%5C
 %22message
 %22: %22
@@ -3253,19 +3253,21 @@
 sage
+%5C
 %22: 
+%5C
 %22msg msg
 %22%0A  
@@ -3262,16 +3262,19 @@
 %22msg msg
+%5C%22 
 %22%0A      
@@ -3283,40 +3283,10 @@
     
++
  
- %25s%0A            %7D%22%22%22.formatted(
 json
@@ -3302,17 +3302,34 @@
 eElement
-)
+%0A            + %22%7D%22
 ;%0A    %7D%0A

revert multiline string refactor in JsonThrowablePatternConverterTests (#81815)