"""
主页面蓝图：首页、home、图片工作台、品牌页、静态文件、Logo
"""
import os
from flask import Blueprint, send_file

from app_common import (
    get_db,
    _render_html,
    _is_session_user_valid,
    login_required,
    admin_required,
    STATIC_DIR,
    BASE_DIR,
)
from flask import redirect, url_for, session

from config import base_url,version

main_bp = Blueprint('main', __name__)


@main_bp.route('/')
def index():
    if session.get('user_id') and _is_session_user_valid():
        return redirect(url_for('main.home'))
    return redirect(url_for('auth.login'))


@main_bp.route('/home')
@login_required
def home():
    try:
        conn = get_db()
        with conn.cursor() as cur:
            cur.execute("SELECT username, is_admin FROM users WHERE id = %s", (session['user_id'],))
            row = cur.fetchone()
        conn.close()
        return _render_html('home.html', username=row.get('username', ''), is_admin=bool(row.get('is_admin')), user_id=session.get('user_id'),baseUrl=base_url,version=version)
    except Exception:
        return _render_html('home.html', username=session.get('username', ''), is_admin=False, user_id=session.get('user_id'),baseUrl=base_url,version=version)


@main_bp.route('/image')
@login_required
def wb():
    return _render_html('index.html')


@main_bp.route('/brand')
@login_required
def brand_page():
    return _render_html('brand.html')


@main_bp.route('/brand-tools')
@login_required
def brand_tools_page():
    html_path = os.path.join(STATIC_DIR, 'brand-tools', 'brand-tools.html')
    if os.path.isfile(html_path):
        return send_file(html_path)
    return _render_html('brand_tools.html')


@main_bp.route('/static/<path:filename>')
def serve_static(filename):
    """提供 static 目录及子目录下的静态文件访问。"""
    filepath = os.path.normpath(os.path.join(STATIC_DIR, filename))
    static_abs = os.path.abspath(STATIC_DIR)
    file_abs = os.path.abspath(filepath)
    if not file_abs.startswith(static_abs) or not os.path.isfile(file_abs):
        return '', 404
    return send_file(file_abs, as_attachment=False)


@main_bp.route('/logo.jpg', methods=['GET'])
def get_logo_image():
    return send_file(os.path.join(BASE_DIR, "logo.jpg"), mimetype='image/jpeg')
