"""
Gateway 路由
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from datetime import datetime
import bcrypt
from app.models import db, Gateway

gateways_bp = Blueprint('gateways', __name__)


@gateways_bp.route('/', methods=['GET'])
@jwt_required()
def get_gateways():
    """获取 Gateway 列表"""
    gateways = Gateway.query.all()
    return jsonify({'gateways': [g.to_dict() for g in gateways]}), 200


@gateways_bp.route('/', methods=['POST'])
@jwt_required()
def register_gateway():
    """注册 Gateway"""
    data = request.get_json()
    
    name = data.get('name')
    url = data.get('url')
    token = data.get('token')
    
    if not all([name, url]):
        return jsonify({'error': 'Missing required fields'}), 400
    
    if Gateway.query.filter_by(name=name).first():
        return jsonify({'error': 'Gateway name already exists'}), 400
    
    # Token 哈希
    token_hash = None
    if token:
        token_hash = bcrypt.hashpw(
            token.encode('utf-8'),
            bcrypt.gensalt()
        ).decode('utf-8')
    
    gateway = Gateway(
        name=name,
        url=url,
        token_hash=token_hash,
        status='offline'
    )
    
    db.session.add(gateway)
    db.session.commit()
    
    return jsonify({'gateway': gateway.to_dict()}), 201


@gateways_bp.route('/<gateway_id>', methods=['DELETE'])
@jwt_required()
def delete_gateway(gateway_id):
    """注销 Gateway"""
    gateway = Gateway.query.get(gateway_id)
    if not gateway:
        return jsonify({'error': 'Gateway not found'}), 404
    
    db.session.delete(gateway)
    db.session.commit()
    
    return jsonify({'message': 'Gateway deleted'}), 200


@gateways_bp.route('/<gateway_id>/status', methods=['GET'])
@jwt_required()
def get_gateway_status(gateway_id):
    """获取 Gateway 状态"""
    gateway = Gateway.query.get(gateway_id)
    if not gateway:
        return jsonify({'error': 'Gateway not found'}), 404
    
    return jsonify({
        'gateway_id': gateway.id,
        'status': gateway.status,
        'agent_count': gateway.agent_count,
        'last_heartbeat': gateway.last_heartbeat.isoformat() if gateway.last_heartbeat else None
    }), 200


@gateways_bp.route('/<gateway_id>/heartbeat', methods=['POST'])
def gateway_heartbeat(gateway_id):
    """Gateway 心跳上报"""
    gateway = Gateway.query.get(gateway_id)
    if not gateway:
        return jsonify({'error': 'Gateway not found'}), 404
    
    gateway.last_heartbeat = datetime.utcnow()
    gateway.status = 'online'
    db.session.commit()
    
    return jsonify({'status': 'ok'}), 200
