# -*- coding: utf-8 -*-

import json
import os

def clean_messages(input_file_path, output_file_path):
    # Проверяем, существует ли входной файл
    if not os.path.exists(input_file_path):
        print(f"Входной файл '{input_file_path}' не найден.")
        return

    try:
        # Открываем и загружаем исходный JSON-файл
        with open(input_file_path, 'r', encoding='utf-8') as infile:
            data = json.load(infile)
    except json.JSONDecodeError as e:
        print(f"Ошибка декодирования JSON: {e}")
        return

    cleaned_messages = []

    # Проходим по всем сообщениям
    for message in data.get('messages', []):
        # Создаем словарь с необходимыми полями
        cleaned_message = {
            'id': message.get('id'),
            'date': message.get('date'),
            'from': message.get('from'),
            'text': ''
        }

        # Обрабатываем поле 'text', объединяя все текстовые элементы
        text_content = message.get('text', '')
        cleaned_message['text'] = extract_text(text_content)

        # Добавляем очищенное сообщение в список
        cleaned_messages.append(cleaned_message)

    # Сохраняем очищенные данные в новый файл
    try:
        with open(output_file_path, 'w', encoding='utf-8') as outfile:
            json.dump({'messages': cleaned_messages}, outfile, ensure_ascii=False, indent=2)
        print(f"Очищенные данные успешно сохранены в '{output_file_path}'.")
    except Exception as e:
        print(f"Ошибка при сохранении файла: {e}")

def extract_text(text_content):
    """
    Извлекает текст из поля 'text', которое может быть строкой, списком или словарем.
    """
    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 ''

if __name__ == "__main__":
    input_file = r'C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-22 (3)\result.json'
    output_file = r'C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-22 (3)\cleaned_result.json'
    clean_messages(input_file, output_file)         (улучши данный код) (пример данных для оброботки {{
 "name": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
 "type": "personal_chat",
 "id": 1458255582,
 "messages": [
  {
   "id": 753351,
   "type": "message",
   "date": "2024-07-21T23:25:53",
   "date_unixtime": "1721593553",
   "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": 753354,
   "type": "message",
   "date": "2024-07-21T23:27:27",
   "date_unixtime": "1721593647",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "text": "Приветик. Всё окей, кушать готовлю. А ты там как?",
   "text_entities": [
    {
     "type": "plain",
     "text": "Приветик. Всё окей, кушать готовлю. А ты там как?"
    }
   ]
  },
  {
   "id": 753356,
   "type": "message",
   "date": "2024-07-21T23:30:07",
   "date_unixtime": "1721593807",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 753354,
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 22,
   "text": "",
   "text_entities": []
  },
  {
   "id": 753357,
   "type": "message",
   "date": "2024-07-21T23:30:46",
   "date_unixtime": "1721593846",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 753354,
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 25,
   "text": "",
   "text_entities": []
  },
  {
   "id": 753358,
   "type": "message",
   "date": "2024-07-21T23:31:20",
   "date_unixtime": "1721593880",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753356,
   "text": "Я с родителями живу😂\nНо татушка заинтересовала",
   "text_entities": [
    {
     "type": "plain",
     "text": "Я с родителями живу😂\nНо татушка заинтересовала"
    }
   ]
  },
  {
   "id": 753359,
   "type": "message",
   "date": "2024-07-21T23:31:48",
   "date_unixtime": "1721593908",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753357,
   "text": "Затихли😂",
   "text_entities": [
    {
     "type": "plain",
     "text": "Затихли😂"
    }
   ]
  },
  {
   "id": 753360,
   "type": "message",
   "date": "2024-07-21T23:31:56",
   "date_unixtime": "1721593916",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753357,
   "text": "Хорошо, что весело)",
   "text_entities": [
    {
     "type": "plain",
     "text": "Хорошо, что весело)"
    }
   ]
  },
  {
   "id": 753361,
   "type": "message",
   "date": "2024-07-21T23:31:58",
   "date_unixtime": "1721593918",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": [
    {
     "type": "link",
     "text": "https://t.me/masimka_CATw"
    }
   ],
   "text_entities": [
    {
     "type": "link",
     "text": "https://t.me/masimka_CATw"
    }
   ]
  },
  {
   "id": 753362,
   "type": "message",
   "date": "2024-07-21T23:32:29",
   "date_unixtime": "1721593949",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 28,
   "text": "",
   "text_entities": []
  },
  {
   "id": 753363,
   "type": "message",
   "date": "2024-07-21T23:32:46",
   "date_unixtime": "1721593966",
   "from": "Миро",
   "from_id": "user1525524847",
   "file": "(File not included. Change data exporting settings to download.)",
   "media_type": "voice_message",
   "mime_type": "audio/ogg",
   "duration_seconds": 17,
   "text": "",
   "text_entities": []
  },
  {
   "id": 753364,
   "type": "message",
   "date": "2024-07-21T23:35:05",
   "date_unixtime": "1721594105",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753362,
   "text": "Вхвэвх",
   "text_entities": [
    {
     "type": "plain",
     "text": "Вхвэвх"
    }
   ]
  },
  {
   "id": 753365,
   "type": "message",
   "date": "2024-07-21T23:35:16",
   "date_unixtime": "1721594116",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753362,
   "text": "Умница",
   "text_entities": [
    {
     "type": "plain",
     "text": "Умница"
    }
   ]
  },
  {
   "id": 753366,
   "type": "message",
   "date": "2024-07-21T23:35:32",
   "date_unixtime": "1721594132",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753363,
   "text": "Вхвэвхвх, окей",
   "text_entities": [
    {
     "type": "plain",
     "text": "Вхвэвхвх, окей"
    }
   ]
  },
  {
   "id": 753367,
   "type": "message",
   "date": "2024-07-21T23:36:36",
   "date_unixtime": "1721594196",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753361,
   "text": "О, прикольную одну нашла",
   "text_entities": [
    {
     "type": "plain",
     "text": "О, прикольную одну нашла"
    }
   ]
  },
  {
   "id": 753369,
   "type": "message",
   "date": "2024-07-21T23:37:02",
   "date_unixtime": "1721594222",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753363,
   "text": "А неважно, что я готовлю😂\nГлавное кухню не спалить",
   "text_entities": [
    {
     "type": "plain",
     "text": "А неважно, что я готовлю😂\nГлавное кухню не спалить"
    }
   ]
  },
  {
   "id": 753370,
   "type": "message",
   "date": "2024-07-21T23:38:55",
   "date_unixtime": "1721594335",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 753367,
   "text": "О какая понравилась",
   "text_entities": [
    {
     "type": "plain",
     "text": "О какая понравилась"
    }
   ]
  },
  {
   "id": 753371,
   "type": "message",
   "date": "2024-07-21T23:39:00",
   "date_unixtime": "1721594340",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 753369,
   "text": "Ппххпхп",
   "text_entities": [
    {
     "type": "plain",
     "text": "Ппххпхп"
    }
   ]
  },
  {
   "id": 753372,
   "type": "message",
   "date": "2024-07-21T23:39:13",
   "date_unixtime": "1721594353",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753370,
   "text": "Ща",
   "text_entities": [
    {
     "type": "plain",
     "text": "Ща"
    }
   ]
  },
  {
   "id": 753373,
   "type": "message",
   "date": "2024-07-21T23:39:30",
   "date_unixtime": "1721594370",
   "from": "Миро",
   "from_id": "user1525524847",
   "reply_to_message_id": 753369,
   "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": 753374,
   "type": "message",
   "date": "2024-07-21T23:40:24",
   "date_unixtime": "1721594424",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753372,
   "text": "А не, не ща. Скачивать нельзя. Ну там цветок один. Я что-то такое сохраняла",
   "text_entities": [
    {
     "type": "plain",
     "text": "А не, не ща. Скачивать нельзя. Ну там цветок один. Я что-то такое сохраняла"
    }
   ]
  },
  {
   "id": 753375,
   "type": "message",
   "date": "2024-07-21T23:40:57",
   "date_unixtime": "1721594457",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "reply_to_message_id": 753373,
   "text": "Вхах",
   "text_entities": [
    {
     "type": "plain",
     "text": "Вхах"
    }
   ]
  },
  {
   "id": 753376,
   "type": "message",
   "date": "2024-07-21T23:41:22",
   "date_unixtime": "1721594482",
   "from": "Миро",
   "from_id": "user1525524847",
   "photo": "(File not included. Change data exporting settings to download.)",
   "width": 729,
   "height": 1278,
   "text": "Тату, лол",
   "text_entities": [
    {
     "type": "plain",
     "text": "Тату, лол"
    }
   ]
  },
  {
   "id": 753377,
   "type": "message",
   "date": "2024-07-21T23:41:25",
   "date_unixtime": "1721594485",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Это ?",
   "text_entities": [
    {
     "type": "plain",
     "text": "Это ?"
    }
   ]
  },
  {
   "id": 753378,
   "type": "message",
   "date": "2024-07-21T23:41:38",
   "date_unixtime": "1721594498",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "text": "О",
   "text_entities": [
    {
     "type": "plain",
     "text": "О"
    }
   ]
  },
  {
   "id": 753379,
   "type": "message",
   "date": "2024-07-21T23:41:40",
   "date_unixtime": "1721594500",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "text": "Оно",
   "text_entities": [
    {
     "type": "plain",
     "text": "Оно"
    }
   ]
  },
  {
   "id": 753380,
   "type": "message",
   "date": "2024-07-21T23:41:53",
   "date_unixtime": "1721594513",
   "edited": "2024-07-22T01:25:52",
   "edited_unixtime": "1721600752",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "text": "Только у меня референсы по-миниатюрнее были",
   "text_entities": [
    {
     "type": "plain",
     "text": "Только у меня референсы по-миниатюрнее были"
    }
   ]
  },
  {
   "id": 753381,
   "type": "message",
   "date": "2024-07-21T23:41:57",
   "date_unixtime": "1721594517",
   "from": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
   "from_id": "user1458255582",
   "text": "И в цвете",
   "text_entities": [
    {
     "type": "plain",
     "text": "И в цвете"
    }
   ]
  },
  {
   "id": 753383,
   "type": "message",
   "date": "2024-07-21T23:45:10",
   "date_unixtime": "1721594710",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Прикольно",
   "text_entities": [
    {
     "type": "plain",
     "text": "Прикольно"
    }
   ]
  },
  {
   "id": 753384,
   "type": "message",
   "date": "2024-07-21T23:45:12",
   "date_unixtime": "1721594712",
   "from": "Миро",
   "from_id": "user1525524847",
   "text": "Чем занимаешься",
   "text_entities": [
    {
     "type": "plain",
     "text": "Чем занимаешься"
    }
   ]
  },} ) (сохрани строки {{
 "name": "𝒲𝒶𝓇𝓂 𝒪𝓃 𝒜 𝒞𝑜𝓁𝒹 𝒩𝒾𝑔𝒽𝓉",
 "type": "personal_chat",
 "id": 1458255582,
 "messages": [})