import io
from flask import Flask, render_template, request, redirect, url_for, abort, send_file
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
import requests

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Bot(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    url = db.Column(db.String(200), nullable=False)
    last_heartbeat = db.Column(db.DateTime, default=datetime.utcnow)


class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    bot_id = db.Column(db.Integer, db.ForeignKey('bot.id', ondelete='CASCADE'), nullable=False)
    content_data = db.Column(db.LargeBinary)
    content_mime_type = db.Column(db.String(50))
    response_data = db.Column(db.LargeBinary)
    response_mime_type = db.Column(db.String(50))
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)


@app.route('/')
def index():
    inactive_time = datetime.utcnow() - timedelta(seconds=60)
    Bot.query.filter(Bot.last_heartbeat < inactive_time).delete()
    db.session.commit()
    bots = Bot.query.all()
    return render_template('index.html', bots=bots)


@app.route('/message/<int:message_id>/content')
def get_message_content(message_id):
    message = Message.query.get_or_404(message_id)
    if not message.content_data:
        abort(404)
    return send_file(
        io.BytesIO(message.content_data),
        mimetype=message.content_mime_type
    )


@app.route('/message/<int:message_id>/response')
def get_message_response(message_id):
    message = Message.query.get_or_404(message_id)
    if not message.response_data:
        abort(404)
    return send_file(
        io.BytesIO(message.response_data),
        mimetype=message.response_mime_type
    )


@app.route('/bot/<int:bot_id>/clear', methods=['POST'])
def clear_chat(bot_id):
    try:
        # Удаляем все сообщения для данного бота
        Message.query.filter_by(bot_id=bot_id).delete()
        db.session.commit()
        return redirect(url_for('bot_chat', bot_id=bot_id))
    except Exception as e:
        return str(e), 500


@app.route('/bot/<int:bot_id>', methods=['GET', 'POST'])
def bot_chat(bot_id):
    bot = Bot.query.get_or_404(bot_id)
    if request.method == 'POST':
        content_data = None
        content_mime_type = None
        message_content = None

        # Обработка входящих данных
        file = request.files.get('file')
        if file and file.filename != '':
            content_data = file.read()
            content_mime_type = file.mimetype or 'application/octet-stream'
        elif 'message' in request.form:
            message_content = request.form['message']
            content_data = message_content.encode('utf-8')
            content_mime_type = 'text/plain'

        try:
            # Отправка данных боту
            files = {}
            data = {}
            if content_mime_type.startswith('image/'):
                file_obj = io.BytesIO(content_data)
                files = {'file': (file.filename, file_obj, content_mime_type)}
            else:
                data = {'message': message_content}

            response = requests.post(f"{bot.url}/process", files=files, data=data)

            # Обработка ответа от бота
            if 'image' in response.headers.get('Content-Type', ''):
                response_data = response.content
                response_mime_type = response.headers.get('Content-Type')
            else:
                response_data = response.json().get('response', '').encode('utf-8')
                response_mime_type = 'text/plain'

            # Сохранение в базу данных
            message = Message(
                bot_id=bot.id,
                content_data=content_data,
                content_mime_type=content_mime_type,
                response_data=response_data,
                response_mime_type=response_mime_type
            )
            db.session.add(message)
            db.session.commit()

        except Exception as e:
            error_message = f"Error: {str(e)}"
            message = Message(
                bot_id=bot.id,
                content_data=content_data,
                content_mime_type=content_mime_type,
                response_data=error_message.encode('utf-8'),
                response_mime_type='text/plain'
            )
            db.session.add(message)
            db.session.commit()

        return redirect(url_for('bot_chat', bot_id=bot.id))

    messages = Message.query.filter_by(bot_id=bot.id).order_by(Message.timestamp).all()
    return render_template('chat.html', bot=bot, messages=messages)


@app.route('/register_bot', methods=['POST'])
def register_bot():
    data = request.json
    name = data.get('name')
    url = data.get('url')
    existing_bot = Bot.query.filter_by(url=url).first()
    if existing_bot:
        existing_bot.last_heartbeat = datetime.utcnow()
        db.session.commit()
        return {'bot_id': existing_bot.id}, 200
    bot = Bot(name=name, url=url)
    db.session.add(bot)
    db.session.commit()
    return {'bot_id': bot.id}, 201


@app.route('/heartbeat/<int:bot_id>', methods=['POST'])
def heartbeat(bot_id):
    bot = Bot.query.get(bot_id)
    if not bot:
        return {'error': 'Bot not found'}, 404
    bot.last_heartbeat = datetime.utcnow()
    db.session.commit()
    return {'status': 'success'}, 200


if __name__ == '__main__':
    with app.app_context():
        db.create_all()

    app.run(host='0.0.0.0', port=5000, debug=True)

<!DOCTYPE html>
<html>
<head>
    <title>Bots List</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #0088cc;
            --background-color: #ffffff;
            --card-bg-color: #ffffff;
            --text-color: #000000;
            --secondary-text: #666666;
            --border-color: #e0e0e0;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }

        @media (prefers-color-scheme: dark) {
            :root {
                --background-color: #1e1e1e;
                --card-bg-color: #2d2d2d;
                --text-color: #ffffff;
                --secondary-text: #a0a0a0;
                --border-color: #3a3a3a;
                --shadow-color: rgba(0, 0, 0, 0.3);
            }
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        body {
            background-color: var(--background-color);
            color: var(--text-color);
            min-height: 100vh;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 32px 24px;
        }

        h1 {
            color: var(--text-color);
            margin-bottom: 32px;
            font-size: 28px;
            font-weight: 700;
        }

        .bots-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 24px;
        }

        .bot-card {
            background: var(--card-bg-color);
            border-radius: 16px;
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 16px;
            box-shadow: 0 4px 6px var(--shadow-color);
            transition: all 0.2s ease;
            text-decoration: none;
            color: inherit;
            border: 1px solid var(--border-color);
        }

        .bot-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 12px var(--shadow-color);
        }

        .bot-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background-color: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 20px;
            flex-shrink: 0;
        }

        .bot-info {
            flex-grow: 1;
            overflow: hidden;
        }

        .bot-name {
            font-weight: 600;
            margin-bottom: 6px;
            font-size: 17px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .bot-status {
            font-size: 14px;
            color: var(--secondary-text);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #00c853;
            box-shadow: 0 0 8px rgba(0, 200, 83, 0.3);
        }

        .no-bots {
            text-align: center;
            padding: 40px;
            color: var(--secondary-text);
            font-size: 16px;
            grid-column: 1 / -1;
        }

        @media (max-width: 600px) {
            .container {
                padding: 24px 16px;
            }

            .bots-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .bot-card {
                padding: 16px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Active Bots</h1>
        <div class="bots-grid">
            {% for bot in bots %}
                <a href="{{ url_for('bot_chat', bot_id=bot.id) }}" class="bot-card">
                    <div class="bot-avatar">{{ bot.name[0] }}</div>
                    <div class="bot-info">
                        <div class="bot-name">{{ bot.name }}</div>
                        <div class="bot-status">
                            <span class="status-indicator"></span>
                            Online
                        </div>
                    </div>
                </a>
            {% else %}
                <div class="no-bots">No active bots found</div>
            {% endfor %}
        </div>
    </div>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
    <title>Chat with {{ bot.name }}</title>
    <style>
        :root {
            --primary-color: #0088cc;
            --background-color: #ffffff;
            --message-bg-user: #0088cc;
            --message-bg-bot: #e5e5ea;
            --text-color: #000000;
            --input-bg-color: #f0f2f5;
            --border-color: #e0e0e0;
        }

        @media (prefers-color-scheme: dark) {
            :root {
                --background-color: #1e1e1e;
                --message-bg-bot: #2d2d2d;
                --text-color: #ffffff;
                --input-bg-color: #2b2b2b;
                --border-color: #3a3a3a;
            }
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }

        body {
            background: var(--background-color);
            color: var(--text-color);
        }

        .chat-container {
            max-width: 800px;
            margin: 0 auto;
            height: 100vh;
            display: flex;
            flex-direction: column;
            background: var(--background-color);
        }

        .chat-header {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            gap: 12px;
            background: var(--background-color);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .chat-messages {
            flex-grow: 1;
            padding: 20px;
            overflow-y: auto;
            background: var(--background-color);
        }

        .message {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
        }

        .message.user {
            flex-direction: row-reverse;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 500;
            flex-shrink: 0;
        }

        .message-content {
            max-width: 75%;
            padding: 12px 16px;
            border-radius: 15px;
            background: var(--message-bg-bot);
            color: var(--text-color);
            position: relative;
            word-break: break-word;
        }

        .clear-button {
            background: #dc3545 !important;
            margin-left: auto;
            padding: 8px 16px;
            font-size: 14px;
        }

        .user .message-content {
            background: var(--message-bg-user);
            color: white !important;
        }

        .message-image {
            max-width: 300px;
            border-radius: 12px;
            margin-top: 8px;
            display: block;
        }

        .input-form {
            background: var(--background-color);
            padding: 16px;
            display: flex;
            gap: 12px;
            border-top: 1px solid var(--border-color);
        }

        input[type="text"] {
            flex-grow: 1;
            padding: 12px 16px;
            border: 1px solid var(--border-color);
            border-radius: 25px;
            outline: none;
            background: var(--input-bg-color);
            color: var(--text-color);
        }

        input[type="file"] {
            color: var(--text-color);
        }

        button {
            background: var(--primary-color);
            color: white !important;
            border: none;
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            transition: opacity 0.2s;
            font-weight: 500;
        }

        button:hover {
            opacity: 0.9;
        }

        .timestamp {
            font-size: 0.75rem;
            color: rgba(255, 255, 255, 0.7);
            margin-top: 6px;
            text-align: right;
        }

        .user .timestamp {
            color: rgba(255, 255, 255, 0.7);
        }

        ::-webkit-file-upload-button {
            background: var(--input-bg-color);
            color: var(--text-color);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 6px 12px;
            margin-right: 8px;
        }

        /* Кнопка назад */
        .back-button {
            color: var(--text-color);
            padding: 8px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.2s;
            margin-right: 12px;
        }

        .back-button:hover {
            background-color: rgba(0, 0, 0, 0.1);
        }

        .back-button svg {
            display: block;
        }

        /* Группировка кнопок в шапке */
        .header-buttons {
            margin-left: auto;
            display: flex;
            gap: 12px;
            align-items: center;
        }

        /* Адаптация для мобильных */
        @media (max-width: 600px) {
            .chat-header h2 {
                font-size: 18px;
            }

            .clear-button {
                padding: 6px 12px;
                font-size: 13px;
            }

            .back-button {
                margin-right: 8px;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <a href="{{ url_for('index') }}" class="back-button">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
                </svg>
            </a>
            <div class="message-avatar">{{ bot.name[0] }}</div>
            <h2 style="color: var(--text-color)">{{ bot.name }}</h2>
            <div class="header-buttons">
                <form method="post" action="{{ url_for('clear_chat', bot_id=bot.id) }}"
                      onsubmit="return confirm('Вы уверены, что хотите очистить историю чата?')">
                    <button type="submit" class="clear-button">Очистить чат</button>
                </form>
            </div>
        </div>

        <div class="chat-messages">
            {% for message in messages %}
                <!-- Сообщение пользователя -->
                <div class="message user">
                    <div class="message-avatar">Y</div>
                    <div class="message-content">
                        {% if message.content_mime_type.startswith('image/') %}
                            <img src="{{ url_for('get_message_content', message_id=message.id) }}" class="message-image">
                        {% else %}
                            <div>{{ message.content_data.decode('utf-8') }}</div>
                        {% endif %}
                        <div class="timestamp">
                            {{ message.timestamp.strftime('%H:%M') }}
                        </div>
                    </div>
                </div>

                <!-- Ответ бота -->
                <div class="message">
                    <div class="message-avatar">{{ bot.name[0] }}</div>
                    <div class="message-content">
                        {% if message.response_mime_type.startswith('image/') %}
                            <img src="{{ url_for('get_message_response', message_id=message.id) }}" class="message-image">
                        {% else %}
                            <div>{{ message.response_data.decode('utf-8') }}</div>
                        {% endif %}
                        <div class="timestamp">
                            {{ message.timestamp.strftime('%H:%M') }}
                        </div>
                    </div>
                </div>
            {% endfor %}
            <div id="end-of-chat"></div>
        </div>

        <form class="input-form" method="post" enctype="multipart/form-data">
            <input type="file" name="file" accept="image/*">
            <input type="text" name="message" placeholder="Type a message...">
            <button type="submit">Send</button>
        </form>
    </div>
    <script>
        function scrollToBottom() {
            const chatMessages = document.querySelector('.chat-messages');
            if (chatMessages) {
                chatMessages.scrollTo({
                    top: chatMessages.scrollHeight,
                    behavior: 'smooth'
                });
            }
        }

        // Скроллим вниз при загрузке страницы
        window.addEventListener('load', scrollToBottom);
    </script>
</body>
</html>

Как мне добавить в список с ботами элемент избранное. Его суть использовать страницу chat и сохранять сообщения в базу и ничего не отвечать