import json
import os
import string
from collections import defaultdict, Counter
from datetime import datetime

def load_json(file_path):
    if not os.path.exists(file_path):
        print(f"Входной файл '{file_path}' не найден.")
        return None
    try:
        with open(file_path, 'r', encoding='utf-8') as infile:
            return json.load(infile)
    except json.JSONDecodeError as e:
        print(f"Ошибка декодирования JSON: {e}")
        return None

def save_json(data, file_path):
    try:
        with open(file_path, 'w', encoding='utf-8') as outfile:
            json.dump(data, outfile, ensure_ascii=False, indent=2)
            print(f"Данные успешно сохранены в '{file_path}'.")
    except Exception as e:
        print(f"Ошибка при сохранении файла: {e}")

def save_html(content, file_path):
    try:
        with open(file_path, 'w', encoding='utf-8') as html_file:
            html_file.write(content)
            print(f"HTML отчет успешно сохранен в '{file_path}'.")
    except Exception as e:
        print(f"Ошибка при сохранении HTML файла: {e}")

def extract_text(text_content):
    if isinstance(text_content, str):
        return text_content
    elif isinstance(text_content, list):
        text_parts = []
        for item in text_content:
            if isinstance(item, str):
                text_parts.append(item)
            elif isinstance(item, dict) and 'text' in item:
                text_parts.append(item['text'])
        return ''.join(text_parts)
    elif isinstance(text_content, dict) and 'text' in text_content:
        return text_content['text']
    else:
        return ''

def tokenize_text(text):
    text = text.lower()
    text = text.translate(str.maketrans('', '', string.punctuation))
    words = text.split()
    return words

def get_time_of_day(hour):
    if 6 <= hour < 12:
        return 'Утро'
    elif 12 <= hour < 18:
        return 'День'
    elif 18 <= hour < 24:
        return 'Вечер'
    else:
        return 'Ночь'

def analyze_data(data):
    cleaned_messages = []
    user_message_counts = {}
    user_message_lengths = defaultdict(list)
    activity_by_hour = defaultdict(int)
    activity_by_weekday = defaultdict(int)
    activity_by_month = defaultdict(int)
    activity_by_time_of_day = defaultdict(int)
    word_counter = Counter()
    user_interactions = defaultdict(lambda: defaultdict(int))
    response_times = defaultdict(list)

    russian_stopwords = set([
        'и', 'в', 'во', 'не', 'что', 'он', 'на', 'я', 'с', 'со',
        'как', 'а', 'то', 'все', 'она', 'так', 'его', 'но', 'да',
        'ты', 'к', 'у', 'же', 'вы', 'за', 'бы', 'по', 'только', 'ее',
        'мне', 'было', 'вот', 'от', 'меня', 'еще', 'нет', 'о', 'из',
        'ему', 'теперь', 'когда', 'даже', 'ну', 'вдруг', 'ли', 'если',
        'уже', 'или', 'ни', 'быть', 'был', 'него', 'до', 'вас', 'нибудь',
        'опять', 'уж', 'вам', 'ведь', 'там', 'потом', 'себя', 'ничего',
        'ей', 'может', 'они', 'тут', 'где', 'есть', 'надо', 'ней', 'для',
        'мы', 'тебя', 'их', 'чем', 'была', 'сам', 'чтобы', 'без', 'будто',
        'чего', 'раз', 'тоже', 'себе', 'под', 'будет', 'ж', 'тогда', 'кто',
        'этот', 'того', 'потому', 'этого', 'какой', 'совсем', 'ним', 'здесь',
        'этом', 'один', 'почти', 'мой', 'тем', 'чтобы', 'нее', 'кажется', 'сюда',
        'туда', 'этой'
    ])

    users = set()

    for message in data.get('messages', []):
        user = message.get('from', 'Неизвестный пользователь')
        if user != 'Неизвестный пользователь':
            users.add(user)

        user_message_counts[user] = user_message_counts.get(user, 0) + 1

        cleaned_message = {
            'id': message.get('id'),
            'date': message.get('date'),
            'from': user,
            'text': ''
        }

        text_content = message.get('text', '')
        cleaned_text = extract_text(text_content)
        cleaned_message['text'] = cleaned_text
        cleaned_messages.append(cleaned_message)

        message_length = len(cleaned_text)
        user_message_lengths[user].append(message_length)

        message_date = message.get('date')
        if message_date:
            try:
                dt = datetime.fromisoformat(message_date)
                hour = dt.hour
                weekday = dt.weekday()  # Monday = 0
                month = dt.month  # January = 1
                time_of_day = get_time_of_day(hour)
                activity_by_hour[hour] += 1
                activity_by_weekday[weekday] += 1
                activity_by_month[month] += 1
                activity_by_time_of_day[time_of_day] += 1
            except ValueError:
                pass

        words = tokenize_text(cleaned_text)
        words = [word for word in words if word.lower() not in russian_stopwords]
        word_counter.update(words)

        # Анализ взаимодействий между пользователями
        if 'reply_to_message_id' in message:
            reply_message_id = message['reply_to_message_id']
            reply_message = next((m for m in data['messages'] if m['id'] == reply_message_id), None)
            if reply_message:
                reply_user = reply_message.get('from', 'Неизвестный пользователь')
                user_interactions[user][reply_user] += 1

    # Анализ времени отклика
    if len(users) == 2:
        users_list = list(users)
        user1, user2 = users_list
        for message in data.get('messages', []):
            user = message.get('from', 'Неизвестный пользователь')
            if user != 'Неизвестный пользователь':
                message_date = message.get('date')
                if message_date:
                    dt = datetime.fromisoformat(message_date)
                    for prev_message in reversed(data['messages']):
                        prev_user = prev_message.get('from', 'Неизвестный пользователь')
                        if prev_user != 'Неизвестный пользователь' and prev_user != user:
                            prev_message_date = prev_message.get('date')
                            if prev_message_date:
                                prev_dt = datetime.fromisoformat(prev_message_date)
                                response_time = (dt - prev_dt).total_seconds()
                                if response_time > 0:
                                    response_times[user].append(response_time)
                                break
    else:
        for message in data.get('messages', []):
            user = message.get('from', 'Неизвестный пользователь')
            if user != 'Неизвестный пользователь':
                message_date = message.get('date')
                if message_date:
                    dt = datetime.fromisoformat(message_date)
                    for prev_message in reversed(data['messages']):
                        prev_user = prev_message.get('from', 'Неизвестный пользователь')
                        if prev_user != 'Неизвестный пользователь' and prev_user != user:
                            prev_message_date = prev_message.get('date')
                            if prev_message_date:
                                prev_dt = datetime.fromisoformat(prev_message_date)
                                response_time = (dt - prev_dt).total_seconds()
                                if response_time > 0:
                                    response_times[prev_user].append(response_time)
                                break

    return {
        'cleaned_messages': cleaned_messages,
        'user_message_counts': user_message_counts,
        'user_message_lengths': user_message_lengths,
        'activity_by_hour': dict(sorted(activity_by_hour.items())),
        'activity_by_weekday': dict(sorted(activity_by_weekday.items())),
        'activity_by_month': dict(sorted(activity_by_month.items())),
        'activity_by_time_of_day': dict(sorted(activity_by_time_of_day.items())),
        'word_counter': word_counter,
        'user_interactions': user_interactions,
        'response_times': response_times
    }

def escape_html(text):
    replacements = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': "&quot;",
        "'": "&#39;"
    }
    return ''.join(replacements.get(c, c) for c in text)

def generate_html(data):
    total_messages = len(data['cleaned_messages'])
    user_average_lengths = {user: round(sum(lengths) / len(lengths), 2) if lengths else 0 for user, lengths in data['user_message_lengths'].items()}
    most_common_words = data['word_counter'].most_common(50)

    hours = list(data['activity_by_hour'].keys())
    messages_per_hour = list(data['activity_by_hour'].values())

    # For weekdays
    weekdays = list(data['activity_by_weekday'].keys())
    messages_per_weekday = list(data['activity_by_weekday'].values())
    weekdays, messages_per_weekday = zip(*sorted(zip(weekdays, messages_per_weekday)))
    weekday_labels = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье']
    weekdays = [weekday_labels[wd] for wd in weekdays]

    # For months
    months = list(data['activity_by_month'].keys())
    messages_per_month = list(data['activity_by_month'].values())
    months, messages_per_month = zip(*sorted(zip(months, messages_per_month)))
    month_labels = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
                    'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']
    months = [month_labels[month - 1] for month in months]

    time_of_day = list(data['activity_by_time_of_day'].keys())
    messages_per_time_of_day = list(data['activity_by_time_of_day'].values())

    html = f"""
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <title>Статистика Чата</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
        <style>
            body {{
                font-family: Arial, sans-serif;
                margin: 20px;
            }}
            table {{
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 40px;
            }}
            th, td {{
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
            }}
            th {{
                background-color: #f2f2f2;
            }}
            h2 {{
                color: #333;
            }}
            .chart-container {{
                width: 100%;
                height: 400px;
                margin-bottom: 40px;
            }}
            .summary {{
                margin-bottom: 40px;
            }}
        </style>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
    </head>
    <body>
        <h1>Статистика Чата</h1>

        <div class="summary">
            <p><strong>Общее количество сообщений:</strong> {total_messages}</p>
        </div>

        <h2>Количество Сообщений на Пользователя</h2>
        <table id="userMessagesTable" class="display">
            <thead>
                <tr>
                    <th>Пользователь</th>
                    <th>Количество Сообщений</th>
                </tr>
            </thead>
            <tbody>
    """

    for user, count in sorted(data['user_message_counts'].items(), key=lambda x: x[1], reverse=True):
        html += f"""
                <tr>
                    <td>{escape_html(user)}</td>
                    <td>{count}</td>
                </tr>
        """
    html += """
            </tbody>
        </table>

        <h2>Средняя Длина Сообщений на Пользователя</h2>
        <table id="userAverageLengthsTable" class="display">
            <thead>
                <tr>
                    <th>Пользователь</th>
                    <th>Средняя Длина Сообщения</th>
                </tr>
            </thead>
            <tbody>
    """

    for user, avg_len in sorted(user_average_lengths.items(), key=lambda x: x[1], reverse=True):
        html += f"""
                <tr>
                    <td>{escape_html(user)}</td>
                    <td>{avg_len}</td>
                </tr>
        """
    html += """
            </tbody>
        </table>

        <h2>Активность Пользователей</h2>
        <div class="chart-container">
            <canvas id="activityByHourChart"></canvas>
        </div>
        <div class="chart-container">
            <canvas id="activityByWeekdayChart"></canvas>
        </div>
        <div class="chart-container">
            <canvas id="activityByMonthChart"></canvas>
        </div>
        <div class="chart-container">
            <canvas id="activityByTimeOfDayChart"></canvas>
        </div>

        <h2>Частотный Анализ Слов (Топ-50)</h2>
        <table id="wordFrequencyTable" class="display">
            <thead>
                <tr>
                    <th>Слово</th>
                    <th>Частота</th>
                </tr>
            </thead>
            <tbody>
    """

    for word, freq in most_common_words:
        html += f"""
                <tr>
                    <td>{escape_html(word)}</td>
                    <td>{freq}</td>
                </tr>
        """
    html += """
            </tbody>
        </table>

        <h2>Анализ Взаимодействий между Пользователями</h2>
        <div class="chart-container">
            <canvas id="userInteractionsChart"></canvas>
        </div>

        <h2>Анализ Времени Отклика</h2>
        <div class="chart-container">
            <canvas id="responseTimesChart"></canvas>
        </div>

        <script>
            // Данные для графика активности по часам
            const activityByHourCtx = document.getElementById('activityByHourChart').getContext('2d');
            const activityByHourChart = new Chart(activityByHourCtx, {
                type: 'bar',
                data: {
                    labels: """ + json.dumps(hours) + """,
                    datasets: [{
                        label: 'Количество Сообщений',
                        data: """ + json.dumps(messages_per_hour) + """,
                        backgroundColor: 'rgba(54, 162, 235, 0.6)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Часы'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Количество Сообщений'
                            }
                        }
                    }
                }
            });

            // Данные для графика активности по дням недели
            const activityByWeekdayCtx = document.getElementById('activityByWeekdayChart').getContext('2d');
            const activityByWeekdayChart = new Chart(activityByWeekdayCtx, {
                type: 'bar',
                data: {
                    labels: """ + json.dumps(weekdays) + """,
                    datasets: [{
                        label: 'Количество Сообщений',
                        data: """ + json.dumps(messages_per_weekday) + """,
                        backgroundColor: 'rgba(255, 99, 132, 0.6)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Дни Недели'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Количество Сообщений'
                            }
                        }
                    }
                }
            });

            // Данные для графика активности по месяцам
            const activityByMonthCtx = document.getElementById('activityByMonthChart').getContext('2d');
            const activityByMonthChart = new Chart(activityByMonthCtx, {
                type: 'bar',
                data: {
                    labels: """ + json.dumps(months) + """,
                    datasets: [{
                        label: 'Количество Сообщений',
                        data: """ + json.dumps(messages_per_month) + """,
                        backgroundColor: 'rgba(75, 192, 192, 0.6)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Месяцы'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Количество Сообщений'
                            }
                        }
                    }
                }
            });

            // Данные для графика активности по времени суток
            const activityByTimeOfDayCtx = document.getElementById('activityByTimeOfDayChart').getContext('2d');
            const activityByTimeOfDayChart = new Chart(activityByTimeOfDayCtx, {
                type: 'bar',
                data: {
                    labels: """ + json.dumps(time_of_day) + """,
                    datasets: [{
                        label: 'Количество Сообщений',
                        data: """ + json.dumps(messages_per_time_of_day) + """,
                        backgroundColor: 'rgba(153, 102, 255, 0.6)',
                        borderColor: 'rgba(153, 102, 255, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Время Суток'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Количество Сообщений'
                            }
                        }
                    }
                }
            });

            // Данные для графика взаимодействий между пользователями
            const userInteractionsCtx = document.getElementById('userInteractionsChart').getContext('2d');
            const userInteractionsChart = new Chart(userInteractionsCtx, {
                type: 'bar',
                data: {
                    labels: """ + json.dumps(list(data['user_interactions'].keys())) + """,
                    datasets: [{
                        label: 'Количество Взаимодействий',
                        data: """ + json.dumps([sum(interactions.values()) for interactions in data['user_interactions'].values()]) + """,
                        backgroundColor: 'rgba(255, 99, 132, 0.6)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Пользователи'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'Количество Взаимодействий'
                            }
                        }
                    }
                }
            });

            // Данные для графика времени отклика
            const responseTimesCtx = document.getElementById('responseTimesChart').getContext('2d');
            const responseTimesChart = new Chart(responseTimesCtx, {
                type: 'bar',
                data: {
                    labels: """ + json.dumps(list(data['response_times'].keys())) + """,
                    datasets: [{
                        label: 'Среднее Время Отклика (секунды)',
                        data: """ + json.dumps([sum(times) / len(times) if times else 0 for times in data['response_times'].values()]) + """,
                        backgroundColor: 'rgba(75, 192, 192, 0.6)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Пользователи'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'Среднее Время Отклика (секунды)'
                            }
                        }
                    }
                }
            });

            // Инициализация DataTables
            $(document).ready(function() {
                $('#userMessagesTable').DataTable({
                    "paging": false,
                    "searching": false,
                    "info": false
                });
                $('#userAverageLengthsTable').DataTable({
                    "paging": false,
                    "searching": false,
                    "info": false
                });
                $('#wordFrequencyTable').DataTable({
                    "paging": false,
                    "searching": false,
                    "info": false
                });
            });
        </script>

    </body>
    </html>
    """

    return html

if __name__ == "__main__":
    input_file = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\result.json"
    output_json = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\cleaned_result.json"
    output_html = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\chat_statistics.html"

    data = load_json(input_file)
    if data:
        analyzed_data = analyze_data(data)
        save_json(analyzed_data['cleaned_messages'], output_json)
        html_content = generate_html(analyzed_data)
        save_html(html_content, output_html)                              (предложи какой функционал можно добавить (кроме анализа эмоций ) ) ( пот пример json :  {
   "id": 875934,
   "type": "message",
   "date": "2024-09-21T18:34:42",
   "date_unixtime": "1726932882",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "Ты справишься",
   "text_entities": [
    {
     "type": "plain",
     "text": "Ты справишься"
    }
   ]
  },
  {
   "id": 875935,
   "type": "message",
   "date": "2024-09-21T18:35:32",
   "date_unixtime": "1726932932",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 875929,
   "text": [
    "Звучиь как топовая подушка ",
    {
     "type": "custom_emoji",
     "text": "🤔",
     "document_id": "video_files/sticker (42).webm"
    },
    ""
   ],
   "text_entities": [
    {
     "type": "plain",
     "text": "Звучиь как топовая подушка "
    },
    {
     "type": "custom_emoji",
     "text": "🤔",
     "document_id": "video_files/sticker (42).webm"
    },
    {
     "type": "plain",
     "text": ""
    }
   ]
  },
  {
   "id": 875936,
   "type": "message",
   "date": "2024-09-21T18:36:31",
   "date_unixtime": "1726932991",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Но вот как бл ее определять на взгляд",
   "text_entities": [
    {
     "type": "plain",
     "text": "Но вот как бл ее определять на взгляд"
    }
   ]
  },
  {
   "id": 875937,
   "type": "message",
   "date": "2024-09-21T18:40:24",
   "date_unixtime": "1726933224",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": [
    "Мне для общего развития честное слово ",
    {
     "type": "custom_emoji",
     "text": "😂",
     "document_id": "video_files/sticker (44).webm"
    },
    ""
   ],
   "text_entities": [
    {
     "type": "plain",
     "text": "Мне для общего развития честное слово "
    },
    {
     "type": "custom_emoji",
     "text": "😂",
     "document_id": "video_files/sticker (44).webm"
    },
    {
     "type": "plain",
     "text": ""
    }
   ]
  },
  {
   "id": 876131,
   "type": "message",
   "date": "2024-09-21T20:57:49",
   "date_unixtime": "1726941469",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "thumbnail": "(File not included. Change data exporting settings to download.)",
   "media_type": "video_message",
   "mime_type": "video/mp4",
   "duration_seconds": 58,
   "width": 384,
   "height": 384,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876132,
   "type": "message",
   "date": "2024-09-21T20:58:34",
   "date_unixtime": "1726941514",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Сложно",
   "text_entities": [
    {
     "type": "plain",
     "text": "Сложно"
    }
   ]
  },
  {
   "id": 876133,
   "type": "message",
   "date": "2024-09-21T20:58:53",
   "date_unixtime": "1726941533",
   "edited": "2024-09-21T20:58:57",
   "edited_unixtime": "1726941537",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 8,
   "text": "Оплплпьп",
   "text_entities": [
    {
     "type": "plain",
     "text": "Оплплпьп"
    }
   ]
  },
  {
   "id": 876134,
   "type": "message",
   "date": "2024-09-21T20:59:00",
   "date_unixtime": "1726941540",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Ахуеть",
   "text_entities": [
    {
     "type": "plain",
     "text": "Ахуеть"
    }
   ]
  },
  {
   "id": 876135,
   "type": "message",
   "date": "2024-09-21T20:59:04",
   "date_unixtime": "1726941544",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "Ахуеть",
   "text_entities": [
    {
     "type": "plain",
     "text": "Ахуеть"
    }
   ]
  },
  {
   "id": 876136,
   "type": "message",
   "date": "2024-09-21T20:59:05",
   "date_unixtime": "1726941545",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "А как?",
   "text_entities": [
    {
     "type": "plain",
     "text": "А как?"
    }
   ]
  },
  {
   "id": 876137,
   "type": "message",
   "date": "2024-09-21T20:59:06",
   "date_unixtime": "1726941546",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Оказывает в гс модно писать",
   "text_entities": [
    {
     "type": "plain",
     "text": "Оказывает в гс модно писать"
    }
   ]
  },
  {
   "id": 876138,
   "type": "message",
   "date": "2024-09-21T20:59:45",
   "date_unixtime": "1726941585",
   "edited": "2024-09-21T21:00:32",
   "edited_unixtime": "1726941632",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 10,
   "text": "Да я увидел одного чела в каком-то канале, это что, голосовый текст, я просто такой офигел просто, я такой вау, я в шоке.",
   "text_entities": [
    {
     "type": "plain",
     "text": "Да я увидел одного чела в каком-то канале, это что, голосовый текст, я просто такой офигел просто, я такой вау, я в шоке."
    }
   ]
  },
  {
   "id": 876139,
   "type": "message",
   "date": "2024-09-21T21:00:45",
   "date_unixtime": "1726941645",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 91,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876142,
   "type": "message",
   "date": "2024-09-21T21:01:17",
   "date_unixtime": "1726941677",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 12,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876143,
   "type": "message",
   "date": "2024-09-21T21:02:47",
   "date_unixtime": "1726941767",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 876139,
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 36,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876144,
   "type": "message",
   "date": "2024-09-21T21:03:08",
   "date_unixtime": "1726941788",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 876142,
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 11,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876145,
   "type": "message",
   "date": "2024-09-21T21:03:14",
   "date_unixtime": "1726941794",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 1,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876156,
   "type": "message",
   "date": "2024-09-21T21:06:33",
   "date_unixtime": "1726941993",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "thumbnail": "(File not included. Change data exporting settings to download.)",
   "media_type": "video_file",
   "mime_type": "video/mp4",
   "duration_seconds": 5,
   "width": 576,
   "height": 1280,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876157,
   "type": "message",
   "date": "2024-09-21T21:06:40",
   "date_unixtime": "1726942000",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Ак без према",
   "text_entities": [
    {
     "type": "plain",
     "text": "Ак без према"
    }
   ]
  },
  {
   "id": 876162,
   "type": "message",
   "date": "2024-09-21T21:07:33",
   "date_unixtime": "1726942053",
   "edited": "2024-09-21T21:08:56",
   "edited_unixtime": "1726942136",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 1,
   "text": "Алаоао",
   "text_entities": [
    {
     "type": "plain",
     "text": "Алаоао"
    }
   ]
  },
  {
   "id": 876165,
   "type": "message",
   "date": "2024-09-21T21:07:58",
   "date_unixtime": "1726942078",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 2,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876166,
   "type": "message",
   "date": "2024-09-21T21:08:34",
   "date_unixtime": "1726942114",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 14,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876168,
   "type": "message",
   "date": "2024-09-21T21:09:10",
   "date_unixtime": "1726942150",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 7,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876169,
   "type": "message",
   "date": "2024-09-21T21:09:11",
   "date_unixtime": "1726942151",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 2,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876170,
   "type": "message",
   "date": "2024-09-21T21:09:20",
   "date_unixtime": "1726942160",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 876168,
   "text": "А вот крутая )",
   "text_entities": [
    {
     "type": "plain",
     "text": "А вот крутая )"
    }
   ]
  },
  {
   "id": 876171,
   "type": "message",
   "date": "2024-09-21T21:09:28",
   "date_unixtime": "1726942168",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Куда топаешь",
   "text_entities": [
    {
     "type": "plain",
     "text": "Куда топаешь"
    }
   ]
  },
  {
   "id": 876179,
   "type": "message",
   "date": "2024-09-21T21:12:07",
   "date_unixtime": "1726942327",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 4,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876183,
   "type": "message",
   "date": "2024-09-21T21:12:41",
   "date_unixtime": "1726942361",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Аааа",
   "text_entities": [
    {
     "type": "plain",
     "text": "Аааа"
    }
   ]
  },
  {
   "id": 876425,
   "type": "message",
   "date": "2024-09-22T11:03:33",
   "date_unixtime": "1726992213",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Доброе утро , как спалось ?",
   "text_entities": [
    {
     "type": "plain",
     "text": "Доброе утро , как спалось ?"
    }
   ]
  },
  {
   "id": 876768,
   "type": "message",
   "date": "2024-09-22T19:21:31",
   "date_unixtime": "1727022091",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 51,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876770,
   "type": "message",
   "date": "2024-09-22T19:34:53",
   "date_unixtime": "1727022893",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Пипец. ..",
   "text_entities": [
    {
     "type": "plain",
     "text": "Пипец. .."
    }
   ]
  },
  {
   "id": 876771,
   "type": "message",
   "date": "2024-09-22T19:35:05",
   "date_unixtime": "1727022905",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Ну у меня скучно",
   "text_entities": [
    {
     "type": "plain",
     "text": "Ну у меня скучно"
    }
   ]
  },
  {
   "id": 876772,
   "type": "message",
   "date": "2024-09-22T19:35:07",
   "date_unixtime": "1727022907",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Еле встал",
   "text_entities": [
    {
     "type": "plain",
     "text": "Еле встал"
    }
   ]
  },
  {
   "id": 876774,
   "type": "message",
   "date": "2024-09-22T19:41:40",
   "date_unixtime": "1727023300",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Встал позавтракать в 17 )",
   "text_entities": [
    {
     "type": "plain",
     "text": "Встал позавтракать в 17 )"
    }
   ]
  },
  {
   "id": 876786,
   "type": "message",
   "date": "2024-09-22T19:42:53",
   "date_unixtime": "1727023373",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Чем занимаешься ?",
   "text_entities": [
    {
     "type": "plain",
     "text": "Чем занимаешься ?"
    }
   ]
  },
  {
   "id": 876818,
   "type": "message",
   "date": "2024-09-22T19:46:02",
   "date_unixtime": "1727023562",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 26,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876826,
   "type": "message",
   "date": "2024-09-22T19:47:46",
   "date_unixtime": "1727023666",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Чай это весело )",
   "text_entities": [
    {
     "type": "plain",
     "text": "Чай это весело )"
    }
   ]
  },
  {
   "id": 876881,
   "type": "message",
   "date": "2024-09-22T21:13:58",
   "date_unixtime": "1727028838",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 3,
   "text": "",
   "text_entities": []
  },
  {
   "id": 876882,
   "type": "message",
   "date": "2024-09-22T21:14:20",
   "date_unixtime": "1727028860",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 1,
   "text": "",
   "text_entities": []
  },
  {
   "id": 877058,
   "type": "message",
   "date": "2024-09-23T02:30:46",
   "date_unixtime": "1727047846",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Спокойной ночи, сладких снов",
   "text_entities": [
    {
     "type": "plain",
     "text": "Спокойной ночи, сладких снов"
    }
   ]
  },
  {
   "id": 877073,
   "type": "message",
   "date": "2024-09-23T07:13:36",
   "date_unixtime": "1727064816",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "Доброе утречко)",
   "text_entities": [
    {
     "type": "plain",
     "text": "Доброе утречко)"
    }
   ]
  },
  {
   "id": 877102,
   "type": "message",
   "date": "2024-09-23T09:01:50",
   "date_unixtime": "1727071310",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Доброе утро, как спалось?",
   "text_entities": [
    {
     "type": "plain",
     "text": "Доброе утро, как спалось?"
    }
   ]
  },
  {
   "id": 877108,
   "type": "message",
   "date": "2024-09-23T09:02:06",
   "date_unixtime": "1727071326",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "Плохо",
   "text_entities": [
    {
     "type": "plain",
     "text": "Плохо"
    }
   ]
  },
  {
   "id": 877109,
   "type": "message",
   "date": "2024-09-23T09:02:08",
   "date_unixtime": "1727071328",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "Тебе?",
   "text_entities": [
    {
     "type": "plain",
     "text": "Тебе?"
    }
   ]
  },
  {
   "id": 877111,
   "type": "message",
   "date": "2024-09-23T09:02:14",
   "date_unixtime": "1727071334",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "Какие планы на сегодня?",
   "text_entities": [
    {
     "type": "plain",
     "text": "Какие планы на сегодня?"
    }
   ]
  },
  {
   "id": 877117,
   "type": "message",
   "date": "2024-09-23T09:03:35",
   "date_unixtime": "1727071415",
   "edited": "2024-09-23T09:03:39",
   "edited_unixtime": "1727071419",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Не выспался )",
   "text_entities": [
    {
     "type": "plain",
     "text": "Не выспался )"
    }
   ]
  },
  {
   "id": 877118,
   "type": "message",
   "date": "2024-09-23T09:03:51",
   "date_unixtime": "1727071431",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 877111,
   "text": "Доделать что делал вчера ночью",
   "text_entities": [
    {
     "type": "plain",
     "text": "Доделать что делал вчера ночью"
    }
   ]
  },
  {
   "id": 877119,
   "type": "message",
   "date": "2024-09-23T09:04:00",
   "date_unixtime": "1727071440",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "А что делал?",
   "text_entities": [
    {
     "type": "plain",
     "text": "А что делал?"
    }
   ]
  },
  {
   "id": 877120,
   "type": "message",
   "date": "2024-09-23T09:04:09",
   "date_unixtime": "1727071449",
   "from": "Миро",
   "from_id": "user1525524847",
   "photo": "(File not included. Change data exporting settings to download.)",
   "width": 576,
   "height": 1280,
   "text": "V1",
   "text_entities": [
    {
     "type": "plain",
     "text": "V1"
    }
   ]
  },
  {
   "id": 877189,
   "type": "message",
   "date": "2024-09-23T09:18:14",
   "date_unixtime": "1727072294",
   "from": "Татьяна Меркулова",
   "from_id": "user1132423719",
   "text": "А это для чего?",
   "text_entities": [
    {
     "type": "plain",
     "text": "А это для чего?"
    }
   ]
  },
  {
   "id": 877418,
   "type": "message",
   "date": "2024-09-23T12:33:38",
   "date_unixtime": "1727084018",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Просто интересно",
   "text_entities": [
    {
     "type": "plain",
     "text": "Просто интересно"
    }
   ]
  },
  {
   "id": 877419,
   "type": "message",
   "date": "2024-09-23T12:33:46",
   "date_unixtime": "1727084026",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Сколько от кого сообщений",
   "text_entities": [
    {
     "type": "plain",
     "text": "Сколько от кого сообщений"
    }
   ]
  },
  {
   "id": 877420,
   "type": "message",
   "date": "2024-09-23T12:33:49",
   "date_unixtime": "1727084029",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "И не ногл статистики",
   "text_entities": [
    {
     "type": "plain",
     "text": "И не ногл статистики"
    }
   ]
  },
  {
   "id": 877421,
   "type": "message",
   "date": "2024-09-23T12:34:05",
   "date_unixtime": "1727084045",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Например в какие дни чаще обшаюьст с каким либо человеком",
   "text_entities": [
    {
     "type": "plain",
     "text": "Например в какие дни чаще обшаюьст с каким либо человеком"
    }
   ]
  }
 ]
})