"""
Main public routes for ScholarPress.
"""

import os
from flask import Blueprint, render_template, request, current_app, send_from_directory
from app.models import Article, Journal, SiteSettings, ContentBlock, Tag

main_bp = Blueprint('main', __name__)


@main_bp.route('/uploads/<path:filename>')
def uploaded_file(filename):
    """Serve uploaded files."""
    upload_folder = current_app.config['UPLOAD_FOLDER']
    return send_from_directory(upload_folder, filename)


@main_bp.route('/')
def home():
    """Homepage with latest articles and featured content."""
    settings = SiteSettings.query.first()
    
    # Get latest published articles
    latest_articles = Article.query.filter_by(is_published=True)\
        .order_by(Article.published_date.desc())\
        .limit(6).all()
    
    # Get active journals
    journals = Journal.query.filter_by(is_active=True)\
        .order_by(Journal.name).all()
    
    # Get homepage content blocks
    content_blocks = {
        block.block_key: block 
        for block in ContentBlock.query.filter_by(page='home', is_active=True).all()
    }
    
    return render_template('public/home.html',
                         settings=settings,
                         latest_articles=latest_articles,
                         journals=journals,
                         content_blocks=content_blocks)


@main_bp.route('/about')
def about():
    """About page."""
    settings = SiteSettings.query.first()
    content_blocks = {
        block.block_key: block 
        for block in ContentBlock.query.filter_by(page='about', is_active=True).all()
    }
    
    return render_template('public/about.html',
                         settings=settings,
                         content_blocks=content_blocks)


@main_bp.route('/journals')
def journals():
    """List all journals."""
    settings = SiteSettings.query.first()
    journals = Journal.query.filter_by(is_active=True)\
        .order_by(Journal.name).all()
    
    return render_template('public/journals.html',
                         settings=settings,
                         journals=journals)


@main_bp.route('/journal/<slug>')
def journal_detail(slug):
    """Journal detail page with its articles."""
    settings = SiteSettings.query.first()
    journal = Journal.query.filter_by(slug=slug, is_active=True).first_or_404()
    
    page = request.args.get('page', 1, type=int)
    per_page = current_app.config.get('ARTICLES_PER_PAGE', 10)
    
    articles = Article.query.filter_by(journal_id=journal.id, is_published=True)\
        .order_by(Article.published_date.desc())\
        .paginate(page=page, per_page=per_page, error_out=False)
    
    return render_template('public/journal_detail.html',
                         settings=settings,
                         journal=journal,
                         articles=articles)


@main_bp.route('/open-access')
def open_access():
    """Open Access information page."""
    settings = SiteSettings.query.first()
    content_blocks = {
        block.block_key: block 
        for block in ContentBlock.query.filter_by(page='open_access', is_active=True).all()
    }
    
    return render_template('public/open_access.html',
                         settings=settings,
                         content_blocks=content_blocks)


@main_bp.route('/for-authors')
def for_authors():
    """Information for authors."""
    settings = SiteSettings.query.first()
    content_blocks = {
        block.block_key: block 
        for block in ContentBlock.query.filter_by(page='for_authors', is_active=True).all()
    }
    
    return render_template('public/for_authors.html',
                         settings=settings,
                         content_blocks=content_blocks)


@main_bp.route('/privacy-policy')
def privacy_policy():
    """Privacy policy page."""
    settings = SiteSettings.query.first()
    content_blocks = {
        block.block_key: block 
        for block in ContentBlock.query.filter_by(page='privacy', is_active=True).all()
    }
    
    return render_template('public/privacy_policy.html',
                         settings=settings,
                         content_blocks=content_blocks)


@main_bp.route('/terms')
def terms():
    """Terms of service page."""
    settings = SiteSettings.query.first()
    content_blocks = {
        block.block_key: block 
        for block in ContentBlock.query.filter_by(page='terms', is_active=True).all()
    }
    
    return render_template('public/terms.html',
                         settings=settings,
                         content_blocks=content_blocks)


@main_bp.context_processor
def inject_settings():
    """Inject site settings into all templates."""
    settings = SiteSettings.query.first()
    return dict(site_settings=settings)
