#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通知模板管理路由
提供 API 和頁面來管理通知模板
"""

from flask import Blueprint, request, jsonify, render_template
from auth import login_required
from services.notification_service import NotificationTemplateService
from services.logger_manager import SystemLogger
from config import SYSTEM_VERSION

sys_log = SystemLogger("NotificationRoutes").get_logger()

notification_bp = Blueprint('notification', __name__)


# ==========================================
# 頁面路由
# ==========================================

@notification_bp.route('/notification_templates')
@login_required
def notification_templates_page():
    """通知模板管理頁面"""
    return render_template('notification_templates.html',
                           system_version=SYSTEM_VERSION,
                           active_page='notification_templates')


# ==========================================
# API 路由
# ==========================================

@notification_bp.route('/api/notification/templates', methods=['GET'])
@login_required
def get_templates():
    """取得所有模板"""
    category = request.args.get('category')
    templates = NotificationTemplateService.get_all_templates(category)
    categories = NotificationTemplateService.get_categories()

    return jsonify({
        'success': True,
        'templates': templates,
        'categories': categories
    })


@notification_bp.route('/api/notification/templates/<code>', methods=['GET'])
@login_required
def get_template(code):
    """取得單一模板"""
    template = NotificationTemplateService.get_template_by_code(code)
    if template:
        return jsonify({'success': True, 'template': template})
    return jsonify({'success': False, 'error': '模板不存在'}), 404


@notification_bp.route('/api/notification/templates/<code>', methods=['PUT'])
@login_required
def update_template(code):
    """更新模板"""
    data = request.get_json()
    if not data:
        return jsonify({'success': False, 'error': '無效的請求資料'}), 400

    result = NotificationTemplateService.update_template(code, data)
    if result['success']:
        sys_log.info(f"[Notification] 模板已更新: {code}")
        return jsonify(result)
    return jsonify(result), 400


@notification_bp.route('/api/notification/templates/<code>/preview', methods=['POST'])
@login_required
def preview_template(code):
    """預覽模板"""
    data = request.get_json() or {}
    variables = data.get('variables', {})

    result = NotificationTemplateService.render_template(code, variables)
    if result and result.get('success'):
        return jsonify(result)
    return jsonify(result or {'success': False, 'error': '渲染失敗'}), 400


@notification_bp.route('/api/notification/render', methods=['POST'])
def render_for_n8n():
    """
    API: 為 n8n 渲染模板
    n8n 可調用此 API 取得格式化的訊息
    """
    data = request.get_json()
    if not data:
        return jsonify({'success': False, 'error': '無效的請求資料'}), 400

    code = data.get('template_code')
    variables = data.get('variables', {})

    if not code:
        return jsonify({'success': False, 'error': '缺少 template_code'}), 400

    result = NotificationTemplateService.render_template(code, variables)
    if result and result.get('success'):
        return jsonify(result)
    return jsonify(result or {'success': False, 'error': '渲染失敗'}), 400


@notification_bp.route('/api/notification/categories', methods=['GET'])
@login_required
def get_categories():
    """取得所有分類"""
    categories = NotificationTemplateService.get_categories()
    return jsonify({'success': True, 'categories': categories})


@notification_bp.route('/api/notification/init', methods=['POST'])
@login_required
def init_templates():
    """初始化預設模板"""
    try:
        NotificationTemplateService.init_default_templates()
        return jsonify({'success': True, 'message': '預設模板已初始化'})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500
