{% extends "base.html" %}
{% block title %}View Responses - Markdown Editor & Responses{% endblock %}
{% block head %}
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
          rel="stylesheet">
    <!-- DataTables CSS -->
    <link rel="stylesheet"
          type="text/css"
          href="https://cdn.datatables.net/2.2.1/css/dataTables.dataTables.min.css">
    <style>
    hr {
        border: 0;
        border-top: 1px solid #e0e0e0;
        margin: 2rem 0;
    }


    .markdown-content h1,
    .markdown-content h2,
    .markdown-content h3,
    .markdown-content h4,
    .markdown-content h5,
    .markdown-content h6 {
        margin-top: 1.5rem;
        margin-bottom: 1rem;
        font-weight: bold;
        border-bottom: 2px solid #e0e0e0;
        padding-bottom: 0.5rem;
    }

    .markdown-content h1::before,
    .markdown-content h2::before,
    .markdown-content h3::before,
    .markdown-content h4::before,
    .markdown-content h5::before,
    .markdown-content h6::before {
        font-family: "Font Awesome 5 Free";
        font-weight: 900;
        margin-right: 0.75rem;
    }

    .markdown-content h1::before {
        content: "\f005";
        /* Star Icon */
        color: #ffc107;
    }

    .markdown-content h2::before {
        content: "\f06d";
        /* Fire Icon */
        color: #dc3545;
    }

    .markdown-content h3::before {
        content: "\f0f3";
        /* Bell Icon */
        color: #17a2b8;
    }

    .markdown-content h4::before {
        content: "\f0e7";
        /* Bolt Icon */
        color: #ff33a6;
    }

    .markdown-content h5::before {
        content: "\f0c0";
        /* Users Icon */
        color: #28a745;
    }

    .markdown-content h6::before {
        content: "\f007";
        /* User Icon */
        color: #fd7e14;
    }

    .markdown-content p {
        margin-bottom: 1rem;
        color: #495057;
    }

    .markdown-content ul,
    .markdown-content ol {
        margin-bottom: 1rem;
        padding-left: 2rem;
    }

    .markdown-content code {
        background-color: #e9ecef;
        padding: 0.2rem 0.4rem;
        border-radius: 4px;
        font-size: 0.875rem;
    }

    /* Table Styling */
    .markdown-content table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 1.5rem;
    }

    .markdown-content th,
    .markdown-content td {
        border: 1px solid #dee2e6;
        padding: 0.75rem;
    }

    .markdown-content th {
        background-color: #f8f9fa;
        font-weight: bold;
    }

    .markdown-content tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    .markdown-content tr:hover {
        background-color: #f1f1f1;
    }

    pre {
        line-height: 125%;
    }

    td.linenos .normal {
        color: inherit;
        background-color: transparent;
        padding-left: 5px;
        padding-right: 5px;
    }

    span.linenos {
        color: inherit;
        background-color: transparent;
        padding-left: 5px;
        padding-right: 5px;
    }

    td.linenos .special {
        color: #000000;
        background-color: #ffffc0;
        padding-left: 5px;
        padding-right: 5px;
    }

    span.linenos.special {
        color: #000000;
        background-color: #ffffc0;
        padding-left: 5px;
        padding-right: 5px;
    }

    .codehilite .hll {
        background-color: #ffffcc
    }

    .codehilite {
        background: #f8f8f8;
    }

    .codehilite .c {
        color: #3D7B7B;
        font-style: italic
    }

    /* Comment */
    .codehilite .err {
        border: 1px solid #FF0000
    }

    /* Error */
    .codehilite .k {
        color: #008000;
        font-weight: bold
    }

    /* Keyword */
    .codehilite .o {
        color: #666666
    }

    /* Operator */
    .codehilite .ch {
        color: #3D7B7B;
        font-style: italic
    }

    /* Comment.Hashbang */
    .codehilite .cm {
        color: #3D7B7B;
        font-style: italic
    }

    /* Comment.Multiline */
    .codehilite .cp {
        color: #9C6500
    }

    /* Comment.Preproc */
    .codehilite .cpf {
        color: #3D7B7B;
        font-style: italic
    }

    /* Comment.PreprocFile */
    .codehilite .c1 {
        color: #3D7B7B;
        font-style: italic
    }

    /* Comment.Single */
    .codehilite .cs {
        color: #3D7B7B;
        font-style: italic
    }

    /* Comment.Special */
    .codehilite .gd {
        color: #A00000
    }

    /* Generic.Deleted */
    .codehilite .ge {
        font-style: italic
    }

    /* Generic.Emph */
    .codehilite .ges {
        font-weight: bold;
        font-style: italic
    }

    /* Generic.EmphStrong */
    .codehilite .gr {
        color: #E40000
    }

    /* Generic.Error */
    .codehilite .gh {
        color: #000080;
        font-weight: bold
    }

    /* Generic.Heading */
    .codehilite .gi {
        color: #008400
    }

    /* Generic.Inserted */
    .codehilite .go {
        color: #717171
    }

    /* Generic.Output */
    .codehilite .gp {
        color: #000080;
        font-weight: bold
    }

    /* Generic.Prompt */
    .codehilite .gs {
        font-weight: bold
    }

    /* Generic.Strong */
    .codehilite .gu {
        color: #800080;
        font-weight: bold
    }

    /* Generic.Subheading */
    .codehilite .gt {
        color: #0044DD
    }

    /* Generic.Traceback */
    .codehilite .kc {
        color: #008000;
        font-weight: bold
    }

    /* Keyword.Constant */
    .codehilite .kd {
        color: #008000;
        font-weight: bold
    }

    /* Keyword.Declaration */
    .codehilite .kn {
        color: #008000;
        font-weight: bold
    }

    /* Keyword.Namespace */
    .codehilite .kp {
        color: #008000
    }

    /* Keyword.Pseudo */
    .codehilite .kr {
        color: #008000;
        font-weight: bold
    }

    /* Keyword.Reserved */
    .codehilite .kt {
        color: #B00040
    }

    /* Keyword.Type */
    .codehilite .m {
        color: #666666
    }

    /* Literal.Number */
    .codehilite .s {
        color: #BA2121
    }

    /* Literal.String */
    .codehilite .na {
        color: #687822
    }

    /* Name.Attribute */
    .codehilite .nb {
        color: #008000
    }

    /* Name.Builtin */
    .codehilite .nc {
        color: #0000FF;
        font-weight: bold
    }

    /* Name.Class */
    .codehilite .no {
        color: #880000
    }

    /* Name.Constant */
    .codehilite .nd {
        color: #AA22FF
    }

    /* Name.Decorator */
    .codehilite .ni {
        color: #717171;
        font-weight: bold
    }

    /* Name.Entity */
    .codehilite .ne {
        color: #CB3F38;
        font-weight: bold
    }

    /* Name.Exception */
    .codehilite .nf {
        color: #0000FF
    }

    /* Name.Function */
    .codehilite .nl {
        color: #767600
    }

    /* Name.Label */
    .codehilite .nn {
        color: #0000FF;
        font-weight: bold
    }

    /* Name.Namespace */
    .codehilite .nt {
        color: #008000;
        font-weight: bold
    }

    /* Name.Tag */
    .codehilite .nv {
        color: #19177C
    }

    /* Name.Variable */
    .codehilite .ow {
        color: #AA22FF;
        font-weight: bold
    }

    /* Operator.Word */
    .codehilite .w {
        color: #bbbbbb
    }

    /* Text.Whitespace */
    .codehilite .mb {
        color: #666666
    }

    /* Literal.Number.Bin */
    .codehilite .mf {
        color: #666666
    }

    /* Literal.Number.Float */
    .codehilite .mh {
        color: #666666
    }

    /* Literal.Number.Hex */
    .codehilite .mi {
        color: #666666
    }

    /* Literal.Number.Integer */
    .codehilite .mo {
        color: #666666
    }

    /* Literal.Number.Oct */
    .codehilite .sa {
        color: #BA2121
    }

    /* Literal.String.Affix */
    .codehilite .sb {
        color: #BA2121
    }

    /* Literal.String.Backtick */
    .codehilite .sc {
        color: #BA2121
    }

    /* Literal.String.Char */
    .codehilite .dl {
        color: #BA2121
    }

    /* Literal.String.Delimiter */
    .codehilite .sd {
        color: #BA2121;
        font-style: italic
    }

    /* Literal.String.Doc */
    .codehilite .s2 {
        color: #BA2121
    }

    /* Literal.String.Double */
    .codehilite .se {
        color: #AA5D1F;
        font-weight: bold
    }

    /* Literal.String.Escape */
    .codehilite .sh {
        color: #BA2121
    }

    /* Literal.String.Heredoc */
    .codehilite .si {
        color: #A45A77;
        font-weight: bold
    }

    /* Literal.String.Interpol */
    .codehilite .sx {
        color: #008000
    }

    /* Literal.String.Other */
    .codehilite .sr {
        color: #A45A77
    }

    /* Literal.String.Regex */
    .codehilite .s1 {
        color: #BA2121
    }

    /* Literal.String.Single */
    .codehilite .ss {
        color: #19177C
    }

    /* Literal.String.Symbol */
    .codehilite .bp {
        color: #008000
    }

    /* Name.Builtin.Pseudo */
    .codehilite .fm {
        color: #0000FF
    }

    /* Name.Function.Magic */
    .codehilite .vc {
        color: #19177C
    }

    /* Name.Variable.Class */
    .codehilite .vg {
        color: #19177C
    }

    /* Name.Variable.Global */
    .codehilite .vi {
        color: #19177C
    }

    /* Name.Variable.Instance */
    .codehilite .vm {
        color: #19177C
    }

    /* Name.Variable.Magic */
    .codehilite .il {
        color: #666666
    }

    /* Literal.Number.Integer.Long */
    </style>
{% endblock %}
{% block content %}
    <div id="spinner"
         class="spinner-border"
         role="status"
         style="display: block;
                margin: 0 auto">
        <span class="visually-hidden">Loading...</span>
    </div>
    <!-- Modal -->
    <div class="modal fade"
         id="myModal"
         tabindex="-1"
         aria-labelledby="exampleModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">Console Window</h1>
                    <button type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="progressContainer">...</div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <!-- End Modal -->
    <br />
    <div class="alert alert-primary alert-dismissible fade show" role="alert">
        <h4 class="alert-heading">Agent Responses</h4>
        <button type="button"
                class="btn-close"
                data-bs-dismiss="alert"
                aria-label="Close"></button>
        <p>Use this page to view and regenerate agent responses.</p>
        <ul>
            <li>
                <em>The prompt template folder is: {{ prompt_template_folder }}</em>
            </li>
            <li>
                <em>The data folder is: {{ data_template_folder }}</em>
            </li>
        </ul>
        <br />
        <button class="btn btn-danger" onclick="refreshAllResponses()">
            <i class="bi bi-arrow-clockwise icon"></i> Refresh All Responses
        </button>
    </div>
    <div class="collapse" id="advSettingsSection">
        <div class="card-body">
            <p class="card-text">Edit advanced settings here!</p>
            <hr />
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="btn-group w-100 mb-3" role="group">
                        <button class="btn btn-secondary" onclick="refreshResponses()">
                            <i class="bi bi-arrow-clockwise icon"></i> Show Responses
                        </button>
                        <button class="btn btn-danger" id="runTestsBtn" onclick="runLocalTest()">
                            <i class="bi bi-play-circle icon"></i> Re-Run
                        </button>
                        <button class="btn btn-outline-dark"
                                id="showConsole"
                                data-bs-toggle="modal"
                                data-bs-target="#myModal">
                            <i class="bi bi-download icon"></i> View Console
                        </button>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="input-group">
                        <label for="maxProcessedEvents" class="input-group-text">Max Processed Events</label>
                        <input type="number" class="form-control" id="maxProcessedEvents" value="1">
                        <label for="eventType" class="input-group-text ms-3">Event Type</label>
                        <select class="form-select" id="eventType">
                            <option value="all">All</option>
                            <option value="iswicket">Wicket</option>
                            <option value="score">Scorecard</option>
                            <option value="status">Status Change</option>
                        </select>
                    </div>
                    <span id="testStatusSpan" class="ms-3"></span>
                </div>
            </div>
        </div>
    </div>
    <div id="responsesContainer"></div>
{% endblock %}
{% block scripts %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script type="text/javascript"
            charset="utf8"
            src="https://cdn.datatables.net/2.2.1/js/dataTables.min.js"></script>
    <script>
    fetchInProgress = false;
    window.addEventListener('load', function () {
        document.getElementById('spinner').style.display = 'none';
    });
    function init_datatables() {
        setTimeout(function () {
            if (!$.fn.DataTable.isDataTable('table')) {
                $('table').DataTable({
                    scrollX: true
                });
            }
        }, 10); // Adjust the timeout as needed
    }
    function get_agent_response(identifier, event_type, agent_name, identifier_group) {
        const buttonId = `${identifier}_${event_type}_${agent_name}`;
        const button = document.getElementById(buttonId);
        const spinner = button.querySelector('.spinner-border');
        const icon = button.querySelector('.icon');

        // Disable the button and show the spinner
        button.disabled = true;
        spinner.style.display = 'inline-block';
        icon.style.display = 'none';

        fetch(`{{ url_for('responses.get_agent_response') }}?identifier=${identifier}&agent_name=${agent_name}&event_type=${event_type}&identifier_group=${identifier_group}`)
            .then(response => response.text())
            .then(html => {
                const modal = document.createElement('div');
                modal.classList.add('modal', 'fade');
                modal.id = 'agentResponseModal';
                modal.tabIndex = -1;
                modal.innerHTML = `
                <div class="modal-dialog modal-xl">
                <div class="modal-content">
                <div class="modal-header">
                <h5 class="modal-title">Agent Response</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                ${html}
                </div>
                <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
                </div>
                </div>
            `;

                document.body.appendChild(modal);

                init_tooltips();

                const bootstrapModal = new bootstrap.Modal(modal);
                bootstrapModal.show();
                modal.addEventListener('hidden.bs.modal', () => {
                    document.body.removeChild(modal);
                });
            })
            .catch(err => {
                console.error('Error fetching agent response:', err);
                alert('Error fetching agent response. Please try again later.');
            })
            .finally(r => {
                // Re-enable the button and hide the spinner
                button.disabled = false;
                spinner.style.display = 'none';
                icon.style.display = 'inline-block';
            }
            );
    }

    function get_agent_inputs(identifier, event_type, agent_name, input_type, identifier_group) {
        fetch(`{{ url_for('responses.get_agent_inputs') }}?identifier=${identifier}&agent_name=${agent_name}&event_type=${event_type}&input_type=${input_type}&identifier_group=${identifier_group}`)
            .then(response => response.text())
            .then(html => {
                const modal = document.createElement('div');
                modal.classList.add('modal', 'fade');
                modal.id = 'agentPromptsModal';
                modal.tabIndex = -1;
                modal.innerHTML = `
            <div class="modal-dialog modal-xl">
            <div class="modal-content border-secondary" style="border-width: 10px;">
            <div class="modal-header">
            <h5 class="modal-title">Agent Input</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
            ${html}
            </div>
            <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
            </div>
            </div>
        `;
                document.body.appendChild(modal);

                init_tooltips();
                init_datatables();
                const bootstrapModal = new bootstrap.Modal(modal);
                bootstrapModal.show();
                modal.addEventListener('hidden.bs.modal', () => {
                    document.body.removeChild(modal);
                });
            })
            .catch(err => {
                console.error('Error fetching agent response:', err);
                alert('Error fetching agent response. Please try again later.');
            });
    }

    function showResponses(element) {
        setActiveNav(element);
        document.getElementById('editSection').style.display = 'none';
        document.getElementById('responsesSection').style.display = 'block';
    }

    function refreshAllResponses() {
        fetch('{{ url_for("responses.get_events") }}')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.text();
            })
            .then(async response => {
                for (const event of JSON.parse(response)) {
                    const eventType = event.event_type;
                    const ballIdentifier = event.identifier;
                    const identifier_group = event.identifier_group;
                    await reRunEventAsync(ballIdentifier, eventType, event.file_name, identifier_group);
                    // wait for fetchInProgress to be false
                    while (fetchInProgress) {
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }
            })
            .catch(err => {
                responsesContainer.innerHTML = "<p class='text-danger'>Error loading responses. Please try again later.</p>";
                console.error('Error fetching responses:', err);
            });
    }

    function refreshResponses() {
        const responsesContainer = document.getElementById('responsesContainer');
        responsesContainer.innerHTML = `
        <div class="d-flex align-items-center">
            <strong role="status">Loading...</strong>
            <div class="spinner-border ms-auto" aria-hidden="true"></div>
        </div>
        `;
        fetch('{{ url_for("responses.get_responses") }}')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.text();
            })
            .then(html => {
                responsesContainer.innerHTML = html;
                $('.event').each(function () {
                    var eventType = $(this).find('.event_type').text().split(':')[1].trim();
                    var ballIdentifier = $(this).find('.identifier').text().split(':')[1].trim();
                    var identifier_group = $(this).find('.identifier_group').text().split(':')[1].trim();
                    getFileContent(ballIdentifier, eventType, identifier_group);
                });
                init_tooltips();
            })
            .catch(err => {
                responsesContainer.innerHTML = "<p class='text-danger'>Error loading responses. Please try again later.</p>";
                console.error('Error fetching responses:', err);
            });
    }

    function toggleStatusSpan() {
        const progressModal = new bootstrap.Modal(document.getElementById('progressModal'));
        const toggleButton = document.querySelector('button[onclick="toggleStatusSpan()"]');
        if (toggleButton.innerText === 'Hide Console') {
            progressModal.hide();
            toggleButton.innerText = 'View Console';
        } else {
            progressModal.show();
            toggleButton.innerText = 'Hide Console';
        }
    }

    function renderPayload(identifier, event_type) {
        window.open(`{{ url_for('responses.get_payload') }}?&identifier=${identifier}&event_type=${event_type}`, '_blank');

    }

    function getFileContent(identifier, event_type, identifier_group) {
        const contentElement = $('#' + identifier + '_' + event_type + ' .markdown-content');
        contentElement.html(`
        <div class="d-flex align-items-center">
            <strong role="status">Loading...</strong>
            <div class="spinner-border ms-auto" aria-hidden="true"></div>
        </div>
        `);


        $.ajax({
            url: '{{ url_for("responses.get_agent_response_from_file") }}',
            type: 'POST',
            data: {
                identifier: identifier,
                event_type: event_type,
                identifier_group: identifier_group
            },
            success: function (response) {
                $('#' + identifier + '_' + event_type + ' .markdown-content').replaceWith(response);
                init_tooltips();
            },
            error: function (error) {
                console.error('Error fetching file content:', error);
            }
        });
    }

    function reRunEventAsync(identifier, event_type, file_name, identifier_group) {
        fetchInProgress = true;
        const contentElement = $('#' + identifier + '_' + event_type + ' .markdown-content');
        contentElement.html(`
        <div class="d-flex align-items-center">
            <strong role="status">Loading...</strong>
            <div class="spinner-border ms-auto" aria-hidden="true"></div>
        </div>
        `);

        $.ajax({
            url: `{{ url_for("responses.rerun_event") }}?&identifier=${identifier}&event_type=${event_type}&file_name=${file_name}&identifier_group=${identifier_group}`,
            type: 'GET',
            success: function (response) {
                getFileContent(identifier, event_type, identifier_group);
            },
            error: function (error) {
                console.error('Error fetching file content:', error);
                contentElement.html('<p class="text-danger">Error loading content. Please try again later.</p>');
            },
            complete: function () {
                fetchInProgress = false;
            }
        });
    }


    document.addEventListener('DOMContentLoaded', function () {
        refreshResponses();
        $('.event').each(function () {
            // Get the event type and ball identifier from the p tags with the class event_type and identifier inside the event div
            var eventType = $(this).find('.event_type').text().split(':')[1].trim();
            var ballIdentifier = $(this).find('.identifier').text().split(':')[1].trim();
            var ballIdentifier = $(this).find('.identifier_group').text().split(':')[1].trim();
            getFileContent(ballIdentifier, eventType, identifier_group);
        });
    });

    function runLocalTest() {
        const runBtn = document.getElementById('runTestsBtn');
        const statusSpan = document.getElementById('testStatusSpan');
        const progressContainer = document.getElementById('progressContainer');
        const maxProcessedEvents = document.getElementById('maxProcessedEvents').value;

        runBtn.disabled = true;
        runBtn.innerText = 'Running...';
        statusSpan.innerText = 'Running tests...';
        progressContainer.innerHTML = '';

        const eventSource = new EventSource(`{{ url_for('responses.run_live_progress') }}?max_processed_events=${maxProcessedEvents}`);

        eventSource.onmessage = function (event) {
            const newLog = document.createElement('pre');
            newLog.textContent = event.data;
            progressContainer.appendChild(newLog);
            progressContainer.scrollTop = progressContainer.scrollHeight;
        };

        eventSource.onerror = function () {
            statusSpan.innerText = 'Tests encountered an error or completed.';
            runBtn.disabled = false;
            runBtn.innerText = 'ReRun';
            eventSource.close();
        };

        eventSource.addEventListener('complete', function () {
            statusSpan.innerText = 'Tests completed successfully.';
            runBtn.disabled = false;
            runBtn.innerText = 'ReRun';
            eventSource.close();
        });

        // Show the modal
        const progressModal = new bootstrap.Modal(document.getElementById('progressModal'));
        progressModal.show();
    }
    </script>
{% endblock %}
