import os
import json
from flask import Flask, render_template, request, jsonify, send_from_directory
from node_engine import NodeEngine
from database import init_db
from config import Config

app = Flask(__name__)
app.config.from_object(Config)

# Ensure directories exist
os.makedirs('configs/nodes', exist_ok=True)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs('static/css', exist_ok=True)
os.makedirs('static/js', exist_ok=True)

# Initialize engine and DB
engine = NodeEngine()
init_db()

@app.route('/')
def index():
    # Reload engine to pick up any manual JSON changes
    nodes_config = engine.get_all_node_configs()
    return render_template('board.html', node_configs=nodes_config)

@app.route('/api/nodes/configs')
def get_node_configs():
    return jsonify(engine.get_all_node_configs())

@app.route('/api/create_node', methods=['POST'])
def create_node():
    node_type_id = request.args.get('type')
    x = int(request.args.get('x', 100))
    y = int(request.args.get('y', 100))
    
    # Get config
    configs = engine.get_all_node_configs()
    node_data = next((c for c in configs if c['id'] == node_type_id), None)
    
    if not node_data:
        return "Node type not found", 404
        
    instance_id = f"inst_{node_type_id}_{os.urandom(2).hex()}"
    return render_template('partials/node.html', 
                          node_data=node_data, 
                          node_instance_id=instance_id, 
                          x=x, y=y)

@app.route('/api/upload_asset', methods=['POST'])
def upload_asset():
    if 'file' not in request.files:
        return "No file", 400
    file = request.files['file']
    if file.filename == '':
        return "No selected file", 400
        
    filename = f"upload_{os.urandom(4).hex()}_{file.filename}"
    upload_dir = os.path.join(app.root_path, 'static', 'uploads')
    os.makedirs(upload_dir, exist_ok=True)
    filepath = os.path.join(upload_dir, filename)
    file.save(filepath)
    
    print(f"File saved to: {filepath}")
    
    # URL for access via browser
    image_url = f"/static/uploads/{filename}"
    
    return f'''
        <div class="result-container">
            <img src="{image_url}" class="generated-art animated fadeIn">
            <div class="meta-info">✅ 上传成功: {file.filename}</div>
            <input type="hidden" name="uploaded_url" value="{image_url}">
        </div>
    '''

@app.route('/api/run_node/<node_id>', methods=['POST'])
def run_node(node_id):
    data = request.form.to_dict()
    result = engine.execute_node(node_id, data)
    
    if result.get('type') == 'image':
        return f'''
            <div class="result-container">
                <img src="{result["url"]}" class="generated-art animated fadeIn">
                <div class="meta-info">处理完成 | 耗时: {result["time"]}s</div>
            </div>
        '''
    else:
        error_msg = result.get('error', '未知错误')
        return f'<div class="error-badge">❌ 错误: {error_msg}</div>'

@app.route('/api/chat', methods=['POST'])
def chat():
    message = request.form.get('message', '')
    return f'''
        <div class="msg user">{message}</div>
        <div class="msg ai">已接收指令。如果您想生成图片，请点击右侧“Nano-banana”节点的“启动生成”按钮。</div>
    '''

if __name__ == '__main__':
    app.run(debug=True, port=5000)
