from flask import Flask, request, render_template, send_from_directory
import os
import subprocess

app = Flask(__name__)

# Directories for file uploads and pipeline outputs
UPLOAD_FOLDER = os.path.abspath('./uploads')
OUTPUT_FOLDER = os.path.abspath('./outputs')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)

# Reference genome mapping
REFERENCE_GENOMES = {
    "Acinetobacter baumannii": "acinetobacter_genome.fa",
    "Klebsiella pneumoniae": "klebsiella_genome.fasta",
    "Pseudomonas aeruginosa": "pseudomonas.fasta",
    "Escherichia coli": "escherichia.fasta"
}

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

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

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

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

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

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

@app.route('/submit-analysis', methods=['POST'])
def submit_analysis():
    try:
        # Collect form data
        organism = request.form.get('organism')
        pipeline = request.form.get('pipeline')
        files1 = request.files.getlist('files1[]')
        files2 = request.files.getlist('files2[]')

        # Validate input
        if not organism or not files1 or not files2:
            return "Error: Missing organism or files", 400

        # Save uploaded files
        saved_files1 = []
        saved_files2 = []
        for file in files1:
            path = os.path.join(UPLOAD_FOLDER, file.filename)
            file.save(path)
            saved_files1.append(path)
        for file in files2:
            path = os.path.join(UPLOAD_FOLDER, file.filename)
            file.save(path)
            saved_files2.append(path)

        # Reference genome selection
        reference_genome = REFERENCE_GENOMES.get(organism)
        if not reference_genome:
            return f"Error: No reference genome for {organism}", 400

        # Log file paths for debugging
        print(f"Files uploaded (1): {[os.path.abspath(f) for f in saved_files1]}")
        print(f"Files uploaded (2): {[os.path.abspath(f) for f in saved_files2]}")
        print(f"Reference genome: {os.path.abspath(reference_genome)}")
        print(f"Output folder: {os.path.abspath(OUTPUT_FOLDER)}")

        # Prepare the Nextflow command with absolute paths
        command = (
            f"nextflow run /var/www/html/anshu/RAPID-engine/SNP1.nf "
            
            f"--fastq1 {' '.join([os.path.abspath(file) for file in saved_files1])} "
            f"--fastq2 {' '.join([os.path.abspath(file) for file in saved_files2])} "
            f"--reference {os.path.abspath(reference_genome)} "
            f"--output {os.path.abspath(OUTPUT_FOLDER)} --pipeline {pipeline}"
        )

        print(f"Executing command: {command}")

        # Run the pipeline and capture output
        process = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        # Log stdout and stderr
        print(f"STDOUT: {process.stdout}")
        print(f"STDERR: {process.stderr}")

        # Save the process output to a log file for debugging
        with open("pipeline_debug.log", "w") as log_file:
            log_file.write(f"Command: {command}\n\n")
            log_file.write(f"STDOUT:\n{process.stdout}\n\n")
            log_file.write(f"STDERR:\n{process.stderr}\n\n")

        # Check if the pipeline executed successfully
        if process.returncode != 0:
            return f"Pipeline execution failed: {process.stderr}", 500

        # Check if output folder has files
        output_files = os.listdir(OUTPUT_FOLDER)
        print(f"Files in output folder after pipeline: {output_files}")
        if not output_files:
            with open("pipeline_debug.log", "a") as log_file:
                log_file.write("Pipeline completed successfully but no output files were found.\n")
                log_file.write(f"Contents of OUTPUT_FOLDER: {os.listdir(OUTPUT_FOLDER)}\n")
            return "Pipeline completed", 500

        return "Pipeline completed successfully. Check outputs for results.", 200
    except Exception as e:
        # Log exceptions for debugging
        with open("pipeline_debug.log", "a") as log_file:
            log_file.write(f"Exception occurred: {str(e)}\n")
        return str(e), 500

@app.route('/output')
def output():
    # List files in the output directory
    files = os.listdir(OUTPUT_FOLDER)
    print(f"Files in output folder: {files}")  # Debugging line to check the files
    if not files:
        return "No output files were generated. Please check the pipeline configuration.", 400
    return render_template('output.html', files=files)

@app.route('/download/<filename>')
def download_file(filename):
    return send_from_directory(OUTPUT_FOLDER, filename)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5001)