// main_tls.js — TLS events analysis
import * as translate from './translate_tls.js'
import { backendUrl } from './config.js'
let lastTlsEvents = [];
let sortFieldTLS = null;
let sortAscTLS = true;
let chartTLS;
let lastSummary = null;
let hasRecentEventsTLS = false;

const byIdTLS = (id) => document.getElementById(id);

const tr = (key) => {
  const lang = localStorage.getItem('lang') || 'ru';
  return translate.translations[lang]?.[key] || key;
};
const applyLanguage = (lang) => {
  const dict = translate.translations[lang] || translate.translations['ru'];
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const key = el.getAttribute('data-i18n');
    if (dict[key]) el.textContent = dict[key];
  });
  localStorage.setItem('lang', lang);
  if (lastSummary) {
    showSummaryTLS(lastSummary.total, lastSummary.anomalies, lastSummary.visible);
  }
};

const initLanguage = () => {
  const lang = localStorage.getItem('lang') || 'ru';
  const select = byIdTLS('langSelectTLS');
  if (select) select.value = lang;
  applyLanguage(lang);
  if (select) {
    select.addEventListener('change', (e) => {
      applyLanguage(e.target.value);
    });
  }
};
const saveTlsState = () => {
  localStorage.setItem('limitTLS', byIdTLS('limitInputTLS').value);
  localStorage.setItem('offsetTLS', byIdTLS('offsetInputTLS').value);
  localStorage.setItem('anomalyOnlyTLS', byIdTLS('anomalyOnlyCheckboxTLS').checked);
  localStorage.setItem('intervalTLS', byIdTLS('intervalSelectTLS').value);
};
const LoadTlsState = () => {
  if (localStorage.getItem('limitTLS')) byIdTLS('limitInputTLS').value = localStorage.getItem('limitTLS');
  if (localStorage.getItem('offsetTLS')) byIdTLS('offsetInputTLS').value = localStorage.getItem('offsetTLS');
  if (localStorage.getItem('anomalyOnlyTLS')) byIdTLS('anomalyOnlyCheckboxTLS').checked = localStorage.getItem('anomalyOnlyTLS') === 'true';
  if (localStorage.getItem('intervalTLS')) byIdTLS('intervalSelectTLS').value = localStorage.getItem('intervalTLS');
};

const analyzeManualTLS = async () => {
  const input = byIdTLS('jsonInputTLS').value;
  const errorBox = byIdTLS('errorTLS');
  const resultBox = byIdTLS('resultTLS');
  errorBox.textContent = '';
  resultBox.innerHTML = '';

  let events;
  try {
    events = JSON.parse(input);
    if (!Array.isArray(events)) throw new Error('Expected array of objects');
  } catch (err) {
    errorBox.textContent = 'Invalid JSON: ' + err.message;
    return;
  }

  try {
    const res = await fetch(`${backendUrl}/ai/analyze/tls`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ events })
    });
    const data = await res.json();

    if (data.error) {
      errorBox.textContent = 'Error: ' + data.error;
    } else {
      resultBox.innerHTML = `
        <p><strong>Total events:</strong> ${data.total}</p>
        <p><strong>Anomalies:</strong> ${data.anomaly_count}</p>
        <pre>${JSON.stringify(data.anomalies, null, 2)}</pre>
      `;
    }
  } catch (err) {
    errorBox.textContent = 'Request error: ' + err.message;
  }
};

const analyzeTlsFromRedis = async () => {
  const limit = parseInt(byIdTLS('limitInputTLS').value) || 100;
  const offset = parseInt(byIdTLS('offsetInputTLS').value) || 0;
  const onlyAnomalies = byIdTLS('anomalyOnlyCheckboxTLS').checked;

  try {
    const res = await fetch(`${backendUrl}/api/analyze/tls?limit=${limit}&offset=${offset}&only_anomalies=${onlyAnomalies}`);
    const data = await res.json();

    if (data.error) throw new Error(data.error);

    lastTlsEvents = data.events;
    hasRecentEventsTLS = data.events.length > 0;
    sortFieldTLS = null;
    sortAscTLS = true;

    byIdTLS('tls-results').innerHTML = '';
    byIdTLS('detailsBoxTLS').innerHTML = '';

    const visibleCount = onlyAnomalies ? limit : data.events.length;
    showSummaryTLS(data.total, data.anomaly_count, visibleCount);
    renderTlsEvents(data.events);
  } catch (err) {
    byIdTLS('tls-results').innerHTML = `<tr><td colspan="8" class="error">Error: ${err.message}</td></tr>`;
  }
};

const showSummaryTLS = (total, anomalies, visible) => {
  const percent = ((anomalies / (visible || 1)) * 100).toFixed(2);
  byIdTLS('summaryBoxTLS').innerHTML = `
    <p><strong>Total in Redis:</strong> ${total} events</p>
    <p><strong>In sample:</strong> ${visible}, Anomalies found: ${anomalies} (${percent}%)</p>
  `;
};

const renderTlsEvents = (events) => {
  const tbody = byIdTLS('tls-results');
  tbody.innerHTML = '';
  events.forEach(({ index, src_ip, dst_ip, anomaly, full }) => {
    const {
      src_port,
      dest_port,
      proto,
      pkt_src
    } = full;

    const row = document.createElement('tr');
    row.className = anomaly ? 'anomaly' : 'normal';
    row.innerHTML = `
      <td>${index + 1}</td>
      <td>${src_ip}:${src_port || ''}</td>
      <td>${dst_ip}:${dest_port || ''}</td>
      <td>${proto || ''}</td>
      <td>${pkt_src || ''}</td>
      <td>${anomaly ? 'Yes🚨' : 'No ✅'}</td>
      <td><button style="font-size: 12px; padding: 2px 6px;" onclick='showDetailsTLS(${JSON.stringify(full)})'>🔍</button></td>
      <td><button style="font-size: 12px; padding: 2px 6px;" onclick='copySuricataRuleTLS("${src_ip}")'>⚡</button></td>
    `;
    tbody.appendChild(row);
  });
};

window.showDetailsTLS = (event) => {
  byIdTLS('detailsBoxTLS').innerHTML = `<h3>Event details:</h3><pre>${JSON.stringify(event, null, 2)}</pre>`;
  byIdTLS('detailsBoxTLS').scrollIntoView({ behavior: 'smooth' });
};
const exportAnomaliesTLS = (format) => {
  const anomalies = lastTlsEvents.filter(e => e.anomaly);
  if (anomalies.length === 0) return alert('No anomalies for export');

  if (format === 'csv') {
    const headers = Object.keys(anomalies[0]);
    const rows = anomalies.map(e => headers.map(h => JSON.stringify(e[h] ?? '')).join(','));
    const csv = [headers.join(','), ...rows].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'tls_anomalies.csv';
    link.click();
  } else {
    const blob = new Blob([JSON.stringify(anomalies, null, 2)], { type: 'application/json' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'tls_anomalies.json';
    link.click();
  }
};

// JS function for generating a rule and showing a modal window
window.copySuricataRuleTLS = (ip) => {
  const rule = `drop ip [${ip}] any -> any any (msg:"Blocked malicious IP ${ip}"; sid:999001; rev:1;)`;
  
  // Insert a rule into a modal window
  const modal = document.getElementById('suricataModal');
  const ruleBox = document.getElementById('suricataRule');
  
  if (modal && ruleBox) {
    ruleBox.textContent = rule;
    modal.style.display = 'block';
  } else {
    alert('Error: Failed to display rule.');
  }
};


byIdTLS('analyzeManualTLS').addEventListener('click', analyzeManualTLS);
byIdTLS('analyzeRedisTLS').addEventListener('click', analyzeTlsFromRedis);
byIdTLS('exportCSVTLS').addEventListener('click', () => exportAnomaliesTLS('csv'));
byIdTLS('exportJSONTLS').addEventListener('click', () => exportAnomaliesTLS('json'));

// Charts
const loadTimelineChartTLS = async () => {
  console.log("start");
  const interval = byIdTLS('intervalSelectTLS').value;
  const limit = parseInt(byIdTLS('limitInputTLS').value) || 100;
  const offset = parseInt(byIdTLS('offsetInputTLS').value) || 0;
  const url = `${backendUrl}/api/analyze_tls_timeline?interval=${interval}&limit=${limit}&offset=${offset}`;

  try {
    const res = await fetch(url);
    const data = await res.json();
    console.log("start mapping");
    const labels = data.timeline.map(t => t.time);
    const values = data.timeline.map(t => t.anomalies);
    console.log("end mapping");
    if (chartTLS) chartTLS.destroy();
    const ctx = byIdTLS('timelineChartTLS').getContext('2d');
    console.log("start charting");
    chartTLS = new Chart(ctx, {
      type: 'line',
      data: {
        labels,
        datasets: [{
          label: `Anomalies (${interval})`,
          data: values,
          fill: false,
          tension: 0.2
        }]
      },
      options: {
        responsive: true,
        scales: { y: { beginAtZero: true } }
      }
    });
  } catch (err) {
    alert('Error loading chart: ' + err.message);
  }
};

const loadCompareChartTLS = async () => {
  const from = parseInt(byIdTLS('fromHourTLS').value);
  const to = parseInt(byIdTLS('toHourTLS').value);
  const url = `${backendUrl}/api/anomaly_tls_compare?from_hour=${from}&to_hour=${to}`;

  try {
    const res = await fetch(url);
    const data = await res.json();
    if (data.error) throw new Error(data.error);

    const ctx = byIdTLS('tlsCompareChart').getContext('2d');
    if (window.compareChartObj) window.compareChartObj.destroy();

    window.compareChartObj = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Today', 'Yesterday'],
        datasets: [{
          label: `Anomalies(${data.interval})`,
          data: [data.today.anomalies, data.yesterday.anomalies],
          backgroundColor: ['#e19435', '#0e56ff']
        }]
      },
      options: {
        scales: { y: { beginAtZero: true } }
      }
    });
  } catch (err) {
    alert('Comparison error: ' + err.message);
  }
};

const loadHourlyCompareChartTLS = async () => {
  const from = parseInt(byIdTLS('fromHourChartTLS').value);
  const to = parseInt(byIdTLS('toHourChartTLS').value);
  const url = `${backendUrl}/api/anomaly_tls_compare_timeline?from_hour=${from}&to_hour=${to}`;

  try {
    const res = await fetch(url);
    const data = await res.json();
    if (data.error) throw new Error(data.error);

    const labels = data.timeline.map(t => t.hour);
    const todayData = data.timeline.map(t => t.today);
    const yesterdayData = data.timeline.map(t => t.yesterday);

    const ctx = byIdTLS('tlsHourlyCompareChart').getContext('2d');
    if (window.hourlyCompareChartObj) window.hourlyCompareChartObj.destroy();

    window.hourlyCompareChartObj = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [
          {
            label: 'Today',
            data: todayData,
            backgroundColor: '#e19435'
          },
          {
            label: 'Yesterday',
            data: yesterdayData,
            backgroundColor: '#0e56ff'
          }
        ]
      },
      options: {
        responsive: true,
        scales: { y: { beginAtZero: true } }
      }
    });
  } catch (err) {
    alert('Error building chart: ' + err.message);
  }
};

// Event listeners
//byId('analyzeManualTLS').addEventListener('click', analyzeManualTLS);
//byIdTLS('analyzeRedis').addEventListener('click', fetchAndAnalyzeTLS);
////byIdTLS('exportCSV').addEventListener('click', () => exportAnomalies('csv'));
//byIdTLS('exportJSON').addEventListener('click', () => exportAnomalies('json'));
byIdTLS('timelineBtnTLS').addEventListener('click', loadTimelineChartTLS);
byIdTLS('compareBtnTLS').addEventListener('click', loadCompareChartTLS);
byIdTLS('hourlyCompareBtnTLS').addEventListener('click', loadHourlyCompareChartTLS);



const exportAnomalies = (format) => {
  const anomalies = lastTlsEvents.filter(e => e.anomaly);
  if (anomalies.length === 0) return alert('No anomalies for export');

  if (format === 'csv') {
    const headers = Object.keys(anomalies[0]);
    const rows = anomalies.map(e => headers.map(h => JSON.stringify(e[h] ?? '')).join(','));
    const csv = [headers.join(','), ...rows].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'anomalies.csv';
    link.click();
  } else {
    const blob = new Blob([JSON.stringify(anomalies, null, 2)], { type: 'application/json' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'anomalies.json';
    link.click();
  }
};

let autoRefreshIntervalTLS = null;

const setupAutoRefreshTLS = () => {
  const checkbox = byIdTLS('autoRefreshTLS');
  if (!checkbox) return;

  if (autoRefreshIntervalTLS) clearInterval(autoRefreshIntervalTLS);

  if (checkbox.checked) {
    autoRefreshIntervalTLS = setInterval(() => {
      if (checkbox.checked && hasRecentEventsTLS) {
        analyzeTlsFromRedis();
      }
    }, 120000); // 120 sec
  }
};

// when the checkbox state changes, we recreate the interval
const autoCheckbox = byIdTLS('autoRefresh');
if (autoCheckbox) {
  autoCheckbox.addEventListener('change', setupAutoRefreshTLS);
}



const sortTLSTableBy = (field) => {
  if (sortFieldTLS === field) {
    sortAscTLS = !sortAscTLS;
  } else {
    sortFieldTLS = field;
    sortAscTLS = true;
  }

  lastTlsEvents.sort((a, b) => {
    const getValue = (obj) => {
      if (field in obj) return obj[field];
      if (obj.full && field in obj.full) return obj.full[field];
      return null;
    };

    const valA = getValue(a);
    const valB = getValue(b);

    if (valA < valB) return sortAscTLS ? -1 : 1;
    if (valA > valB) return sortAscTLS ? 1 : -1;
    return 0;
  });

  renderTlsEvents(lastTlsEvents);
};
document.querySelectorAll('th[data-sort]').forEach(th => {
  th.addEventListener('click', () => sortTLSTableBy(th.dataset.sort));
});
LoadTlsState();
// Init

setupAutoRefreshTLS();
//initLanguageTLS();

