import os
from flask import Flask, render_template, request, redirect, url_for, session, send_file
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'dev_secret_key')
app.config['SESSION_COOKIE_NAME'] = "task_session"

FLAG1 = os.environ.get('FLAG1', 'vsosh{r0b0ts_wh1sp3rs_th3_h1dd3n_p4th}')
FLAG2 = os.environ.get('FLAG2', 'vsosh{4nc13nt_c1ty_s3cr3t_h4ll_unl0ck3d}')

users = {}


@app.route('/')
def index():
    username = session.get('username')
    role = session.get('role', 'player')
    return render_template('index.html', username=username, role=role)


@app.route('/robots.txt')
def robots():
    return send_file('robots.txt', mimetype='text/plain')


@app.route('/ancient-city/warden-portal-7f3b1e29-84c1-4d5e-9a62-5b72c2890c1e')
def secret_portal():
    return render_template('secret.html', flag=FLAG1)


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username', '').strip()
        password = request.form.get('password', '')
        
        role = request.form.get('role', 'player')
        
        if not username or not password:
            return render_template('register.html', error='Никнейм и пароль обязательны')
        
        if username in users:
            return render_template('register.html', error='Пользователь уже существует')
        
        users[username] = {
            'password': generate_password_hash(password),
            'role': role
        }
        
        return redirect(url_for('login'))
    
    return render_template('register.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username', '').strip()
        password = request.form.get('password', '')
        
        if username in users:
            user = users[username]
            if check_password_hash(user['password'], password):
                session['username'] = username
                session['role'] = user.get('role', 'player')
                return redirect(url_for('portal'))
        
        return render_template('login.html', error='Неверный никнейм или пароль')
    
    return render_template('login.html')


@app.route('/portal')
def portal():
    if 'username' not in session:
        return redirect(url_for('login'))
    
    username = session.get('username')
    role = session.get('role', 'player')
    
    return render_template('portal.html', username=username, role=role)


@app.route('/secret-hall')
def secret_hall():
    if 'username' not in session:
        return redirect(url_for('login'))
    
    role = session.get('role', 'player')
    
    if role != 'admin':
        return render_template('admin.html', 
                             error='Доступ запрещён. Только избранные могут войти сюда.')
    
    username = session.get('username')
    return render_template('admin.html', username=username, flag=FLAG2)


@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))


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

