#Kemoverse - a gacha-style bot for the Fediverse.
#Copyright © 2025 Waifu
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as
#published by the Free Software Foundation, either version 3 of the
#License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU Affero General Public License for more details.
#
#You should have received a copy of the GNU Affero General Public License
#along with this program.  If not, see https://www.gnu.org/licenses/.

import sqlite3
import sys
import os

# Add bot directory to path to import config
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'bot'))
import config

from flask import Flask, render_template, abort
from werkzeug.exceptions import HTTPException

app = Flask(__name__)

def get_db_connection():
    conn = sqlite3.connect(config.DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def get_db_cursor():
    """Get a database cursor."""
    if not hasattr(get_db_cursor, 'conn'):
        get_db_cursor.conn = get_db_connection()
    return get_db_cursor.conn.cursor()

@app.errorhandler(HTTPException)
def handle_exception(error):
    return render_template("_error.html", error=error), error.code

@app.route("/i404")
def i404():
    return abort(404)

@app.route('/')
def index():
    conn = get_db_connection()
    players = conn.execute('SELECT id, username FROM players').fetchall()
    top_players = conn.execute('''
        SELECT players.id, players.username, COUNT(pulls.id) AS pull_count
        FROM players
        LEFT JOIN pulls ON players.id = pulls.player_id
        GROUP BY players.id
        ORDER BY pull_count DESC
        LIMIT 5
    ''').fetchall()

    conn.close()
    return render_template('index.html', players=players, top_players=top_players)

@app.route('/player/<int:id>')
def player_profile(id):
    conn = get_db_connection()
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()

    cursor.execute('SELECT * FROM players WHERE id = ?', (id,))
    player = cursor.fetchone()
    if player is None:
        abort(404)

    cursor.execute('''
        SELECT pulls.timestamp, cards.name as card_name, cards.rarity
        FROM pulls
        JOIN cards ON pulls.card_id = cards.id
        WHERE pulls.player_id = ?
        ORDER BY pulls.timestamp DESC
    ''', (id,))
    pulls = cursor.fetchall()

    conn.close()
    return render_template('player.html', player=player, pulls=pulls)

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

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

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

@app.route('/players')
def player_list():
    # Replace with your actual player fetching logic

    cursor = get_db_cursor()
    cursor.execute('SELECT * FROM players')
    players = cursor.fetchall()
    if not players:
        return render_template('player_list.html', players=[])
    return render_template('player_list.html', players=players)

if __name__ == '__main__':
    app.run(host=config.BIND_ADDRESS, port=config.WEB_PORT, debug=True)