from flask import Flask, render_template, request, send_from_directory, jsonify
import os
from model import process_all  # Make sure to have your processing logic ready in model.py

app = Flask(__name__)

# @app.route('/')
# def index():
#     return render_template('index.html')


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/autowriter')
def index():
    return render_template('autowriter.html')


@app.route('/download-example')
def download_example():
    return send_from_directory(directory='static/res', path='ejemplo.xlsx', as_attachment=True)

@app.route('/download-guide')
def download_guide():
    return send_from_directory(directory='static/res', path='Guia_AutoWriter.pdf', as_attachment=True)

@app.route('/files/<path:filename>')
def download_file(filename):
    return send_from_directory(directory='downloads', path=filename, as_attachment=True)

@app.route('/files/<filename>')
def serve_file(filename):
    return send_from_directory('downloads', filename)

@app.route('/process', methods=['POST'])
def process_data():
    header_text = request.form['headerText']
    footer_text = request.form['footerText']
    file = request.files['fileUpload']
    
    if file:
        filepath = os.path.join('uploads', file.filename)
        file.save(filepath)

        word_path, map_path = process_all(filepath, header_text, footer_text)
        
        os.remove(filepath)  # Clean up the uploaded file
        
        # Return relative paths for client-side use
        return jsonify({'wordPath': os.path.join('files', os.path.basename(word_path)), 
                        'mapPath': os.path.join('files', os.path.basename(map_path))})
    else:
        return jsonify({'error': 'No file provided'}), 400


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