from flask import Blueprint, render_template, request, redirect, url_for, session
from web.services.web_service import WebService
from web.auth import admin_required

bp = Blueprint('wiki', __name__, url_prefix='/wiki')

@bp.route('/')
def index():
    pages = WebService.get_all_wiki_pages()
    return render_template('wiki/index.html', pages=pages)

@bp.route('/view/<path:page_path>')
def view(page_path):
    page = WebService.get_wiki_page(page_path)
    if not page:
        # If admin, offer to create
        if session.get('is_admin'):
            return redirect(url_for('wiki.edit', page_path=page_path))
        return "Page not found", 404
    return render_template('wiki/view.html', page=page)

@bp.route('/edit/<path:page_path>', methods=['GET', 'POST'])
@admin_required
def edit(page_path):
    if request.method == 'POST':
        title = request.form.get('title')
        content = request.form.get('content')
        WebService.save_wiki_page(page_path, title, content, 'admin')
        return redirect(url_for('wiki.view', page_path=page_path))
        
    page = WebService.get_wiki_page(page_path)
    return render_template('wiki/edit.html', page=page, page_path=page_path)
