from flask import Flask, render_template, redirect, request, session, url_for

app = Flask(__name__)

users = {
    'thegamer': 'gamerpro1',
    'justuser': 'randompassword'
}

posts = [
    {"alias": "advices", "title": "Advices for game developers", "image": "advice.png"},
    {"alias": "design-and-music", "title": "Design and music", "image": "design-and-music.png"},
    {"alias": "expectations", "title": "Game expectations vs. reality", "image": "developers-be-like.png"},
    {"alias": "update-1-1", "title": "Game 'Picture Puzzle remake' update 1.1", "image": "skeleton.png"},
    {"alias": "chatgpt", "title": "ChatGPT as code helper", "image": "chatgpt-meme.png"},
    {"alias": "difficulties", "title": "Difficulties while making game", "image": "staircase-fail.png"},
    {"alias": "how-it-was-made", "title": "How the 'Picture Puzzle remake' was made", "image": "coding.png"},
    {"alias": "update-1", "title": "Game 'Picture Puzzle remake' update 1.0", "image": "baobab.png"},
    {"alias": "history", "title": "Picture Puzzle history", "image": "picture-puzzle.png"}
]

def fetch_latest_posts():
    return posts

@app.route("/")
def index():
    latest_posts = fetch_latest_posts()
    return render_template("index.html", latest_posts=latest_posts)

@app.route("/posts")
def all_posts():
    return render_template("posts.html", posts=posts)

@app.route("/about")
def about():
    return render_template("about.html")

@app.route("/posts/<alias>")
def post(alias):
    post_info = next((p for p in posts if p['alias'] == alias), None)
    if post_info:
        return render_template(f"{alias}.html")
    else:
        return "Post not found", 404

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        if username in users and users[username] == password:
            session["username"] = username
            return redirect(url_for("index"))
    return render_template("auth/login.html")

@app.route("/logout")
def logout():
    session.pop("username", None)
    return redirect(url_for("index"))

@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        users[username] = password
        return redirect(url_for("login"))
    return render_template("auth/register.html")

if __name__ == "__main__":
    app.run(debug=True)