from flask import request, render_template, Blueprint, session, current_app, jsonify, flash, redirect, url_for
from flask_security import roles_required, roles_accepted
from flask_wtf.csrf import generate_csrf
import os
import requests

from common.models.document import Catalog
from common.models.user import Tenant
from common.utils.database import Database
from common.utils.nginx_utils import prefixed_url_for
from .basic_forms import SessionDefaultsForm
from common.extensions import content_manager

import markdown

basic_bp = Blueprint('basic_bp', __name__)

# Markdown filter toevoegen aan Jinja2
@basic_bp.app_template_filter('markdown')
def render_markdown(text):
    return markdown.markdown(text, extensions=['tables', 'fenced_code'])


@basic_bp.before_request
def log_before_request():
    current_app.logger.debug(f'Before request: {request.path} =====================================')


@basic_bp.after_request
def log_after_request(response):
    return response


@basic_bp.route('/', methods=['GET', ])
def index():
    return render_template('index.html')


@basic_bp.route('/confirm_email_ok', methods=['GET', ])
def confirm_email_ok():
    return render_template('basic/confirm_email_ok.html')


@basic_bp.route('/confirm_email_fail', methods=['GET', ])
def confirm_email_fail():
    return render_template('basic/confirm_email_fail.html')


@basic_bp.route('/session_defaults', methods=['GET', 'POST'])
@roles_accepted('Super User', 'Partner Admin', 'Tenant Admin')
def session_defaults():
    try:
        # Get tenant session
        tenant_id = session.get('tenant').get('id')
        tenant_db = Database(tenant_id)
        tenant_session = tenant_db.get_session()

        try:
            form = SessionDefaultsForm()

            if form.validate_on_submit():
                if form.catalog.data:
                    catalog_id = int(form.catalog.data)
                    catalog = tenant_session.query(Catalog).get(catalog_id)
                    if catalog:
                        session['catalog_id'] = catalog.id
                        session['catalog_name'] = catalog.name
                else:
                    session.pop('catalog_id', None)
                    session.pop('catalog_name', None)

                flash('Session defaults updated successfully', 'success')
                return redirect(prefixed_url_for('basic_bp.index', for_redirect=True))

            return render_template('basic/session_defaults.html', form=form)

        finally:
            tenant_session.close()

    except Exception as e:
        current_app.logger.error(f"Error in session_defaults: {str(e)}")
        flash('Error accessing catalog data. Please ensure your session is valid.', 'danger')
        return redirect(prefixed_url_for('security_bp.login', for_redirect=True))


@basic_bp.route('/set_user_timezone', methods=['POST'])
def set_user_timezone():
    data = request.get_json()
    timezone = data.get('timezone')

    if timezone:
        session['admin_user_timezone'] = timezone
        return jsonify({'status': 'success', 'timezone': timezone}), 200
    else:
        return jsonify({'status': 'error', 'message': 'Timezone not provided'}), 400


@basic_bp.route('/health', methods=['GET'])
def health():
    return jsonify({'status': 'ok'}), 200


@basic_bp.route('/check_csrf', methods=['GET'])
def check_csrf():
    csrf_token = generate_csrf()
    return jsonify({
        'csrf_token_in_session': session.get('csrf_token'),
        'generated_csrf_token': csrf_token,
        'session_id': session.sid if hasattr(session, 'sid') else None,
        'session_data': dict(session)
    })


@basic_bp.route('/content/<content_type>', methods=['GET'])
@roles_accepted('Super User', 'Partner Admin', 'Tenant Admin')
def view_content(content_type):
    """
    Show content like release notes, terms of use, etc.

    Args:
        content_type (str): Type content (eg. 'changelog', 'terms', 'dpa')
    Request Args:
        version (str): Major.Minor version of the content to display
        patch (str): Patch version of the content to display
    """
    try:
        major_minor = request.args.get('version')
        patch = request.args.get('patch')

        # Gebruik de ContentManager om de content op te halen
        content_data = content_manager.read_content(content_type, major_minor, patch)

        if not content_data:
            flash(f'Content van type {content_type} werd niet gevonden.', 'danger')
            return redirect(prefixed_url_for('basic_bp.index', for_redirect=True))

        # Titels en beschrijvingen per contenttype
        titles = {
            'changelog': 'Release Notes',
            'terms': 'Terms & Conditions',
            'dpa': 'Data Privacy Agreement',
            # Voeg andere types toe indien nodig
        }

        descriptions = {
            'changelog': 'EveAI Release Notes',
            'terms': "Terms & Conditions for using AskEveAI's Evie",
            'dpa': "Data Privacy Agreement for AskEveAI's Evie",
            # Voeg andere types toe indien nodig
        }

        return render_template(
            'basic/view_markdown.html',
            title=titles.get(content_type, content_type.capitalize()),
            description=descriptions.get(content_type, ''),
            markdown_content=content_data['content'],
            version=content_data['version']
        )
    except Exception as e:
        current_app.logger.error(f"Error displaying content {content_type}: {str(e)}")
        flash(f'Error displaying content: {str(e)}', 'danger')
        return redirect(prefixed_url_for('basic_bp.index', for_redirect=True))

@basic_bp.route('/release_notes', methods=['GET'])
@roles_accepted('Super User', 'Partner Admin', 'Tenant Admin')
def release_notes():
    """Doorverwijzen naar de nieuwe content view voor changelog"""
    return redirect(prefixed_url_for('basic_bp.view_content', content_type='changelog', for_redirect=True))
