import os
import base64
import pickle
from flask import Flask, render_template, request

app = Flask(__name__)
app.config['SESSION_COOKIE_NAME'] = "task_session"

FLAG = os.environ.get('FLAG', 'vsosh{s3a_p1ckl3s_n3v3r_trust_d3s3r1al1z3}')


EXAMPLE_COLLECTION = [
    {'name': 'Обычный морской огурец', 'count': 2, 'glow': False},
    {'name': 'Светящийся морской огурец', 'count': 1, 'glow': True},
    {'name': 'Коралловый огурец', 'count': 3, 'glow': False},
]


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/collection', methods=['GET', 'POST'])
def collection():
    if request.method == 'GET':
        return render_template('collection.html', result=None, items=None, total_count=None)

    raw = request.form.get('save_data', '').strip()
    if not raw:
        return render_template('collection.html', result=None, items=None, total_count=None, error='Пришлите сохранение (save_data).')

    try:
        data = base64.b64decode(raw)
    except Exception:
        return render_template('collection.html', result=None, items=None, total_count=None, error='Сохранение должно быть в base64.')

    try:
        collection_data = pickle.loads(data)
    except Exception as e:
        return render_template('collection.html', result=None, items=None, total_count=None, error=f'Не удалось загрузить коллекцию: {e}')

    if not isinstance(collection_data, list):
        collection_data = [collection_data]

    items = []
    for el in collection_data:
        if isinstance(el, dict) and 'name' in el:
            items.append({
                'name': str(el.get('name', '')),
                'count': int(el.get('count', 1)) if isinstance(el.get('count'), (int, float)) else 1,
                'glow': bool(el.get('glow', False)),
            })
        else:
            items.append({'name': str(el)[:80], 'count': 1, 'glow': False})
    total_count = sum(item['count'] for item in items)

    return render_template(
        'collection.html',
        result=f'Коллекция загружена! Морских огурцов: {total_count}',
        items=items,
        total_count=total_count,
    )


@app.route('/collection/example')
def collection_example():
    example_b64 = base64.b64encode(pickle.dumps(EXAMPLE_COLLECTION)).decode()
    return render_template(
        'example.html',
        example_b64=example_b64,
        items=EXAMPLE_COLLECTION,
        total_count=sum(item['count'] for item in EXAMPLE_COLLECTION),
    )


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)
