from flask import Flask, render_template, request, g, redirect, url_for, send_from_directory
import sqlite3
import os

app = Flask(__name__)
DATABASE = 'wiki.db'

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

@app.route('/')
def home():
    cur = get_db().cursor()
    cur.execute('SELECT id, title, summary FROM pages ORDER BY id DESC LIMIT 10')
    pages = cur.fetchall()
    return render_template('home.html', pages=pages)

@app.route('/search')
def search():
    q = request.args.get('q', '')

    waf_blocked = ['--', '#', '/*', '*/', 'union', 'sleep', 'benchmark', 'load_file', 'order']
    if any(bad in q.lower() for bad in waf_blocked):
        return render_template('search.html', results=[], q=q, error="Blocked by WAF.")

    if q.count("'") % 2 != 0:
        return render_template('search.html', results=[], q=q, error="Unbalanced quotes")

    sql = f"""
        SELECT id, title, summary FROM pages
        WHERE title LIKE '%{q}%'
           OR overview LIKE '%{q}%'
           OR appearance LIKE '%{q}%'
           OR obtainment LIKE '%{q}%'
        LIMIT 20
    """
    try:
        cur = get_db().cursor()
        cur.execute(sql)
        results = cur.fetchall()
        return render_template('search.html', results=results, q=q)
    except Exception as e:
        return render_template('search.html', results=[], q=q, error="Search error")

@app.route('/page/<int:page_id>')
def detail(page_id):
    cur = get_db().cursor()
    cur.execute('SELECT id, title, overview, appearance, obtainment, produce_image FROM pages WHERE id = ?', (page_id,))
    page = cur.fetchone()
    if not page:
        return render_template('404.html'), 404
    image_url = None
    if page[5]:
        image_url = url_for('static', filename=f'images/{page[5]}')
    return render_template('detail.html', page=page, image_url=image_url)

if __name__ == '__main__':
    app.run(port=5001, debug=True) 