#!/usr/bin/env python3

import sys
import subprocess
import os
from importlib import import_module

MUMEMTO_VERSION = "1.3.0"

def run_mumemto(args):
    """Run the C++ executable with given args"""
    script_dir = os.path.dirname(os.path.abspath(__file__))
    exec_path = os.path.join(script_dir, 'mumemto_exec')
    if not os.path.exists(exec_path):
        print("Error: mumemto not installed. Please use make to install mumemto first", file=sys.stderr)
        sys.exit(1)
    cmd = [exec_path] + args
    subprocess.run(cmd)

def run_viz(args):
    """Run visualization with given args"""
    try:
        if '--interactive' in args:
            # Remove --interactive flag and import viz_mums_interactive
            args.remove('--interactive')
            viz = import_module('mumemto.viz_mums_interactive')
        else:
            viz = import_module('mumemto.viz_mums')
        
        parsed_args = viz.parse_arguments(args)
        viz.main(parsed_args)
    except ImportError:
        # Fall back to running script directly
        script_dir = os.path.dirname(os.path.abspath(__file__))
        if '--interactive' in args:
            script = os.path.join(script_dir, '_mumemto', 'viz_mums_interactive.py')
        else:
            script = os.path.join(script_dir, '_mumemto', 'viz_mums.py')
        
        if not os.path.exists(script):
            if '--interactive' in args:
                print(f"Error: mumemto not installed. Please run mumemto/viz_mums_interactive.py directly.", file=sys.stderr)
            else:
                print(f"Error: mumemto not installed. Please run mumemto/viz_mums.py directly.", file=sys.stderr)
            sys.exit(1)
        subprocess.run([sys.executable, script] + args)

def run_inversions(args):
    """Run inversion detection"""
    try:
        inversions = import_module('mumemto.find_inversions')
        parsed_args = inversions.parse_arguments(args)
        inversions.main(parsed_args)
    except ImportError:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        script = os.path.join(script_dir, '_mumemto', 'find_inversions.py')
        if not os.path.exists(script):
            print(f"Error: mumemto not installed. Please run mumemto/find_inversions.py directly.", file=sys.stderr)
            sys.exit(1)
        subprocess.run([sys.executable, script] + args)

def run_coverage(args):
    """Run MUM coverage analysis"""
    try:
        coverage = import_module('mumemto.mum_coverage')
        parsed_args = coverage.parse_arguments(args)
        coverage.main(parsed_args)
    except ImportError:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        script = os.path.join(script_dir, '_mumemto', 'mum_coverage.py')
        if not os.path.exists(script):
            print(f"Error: mumemto not installed. Please run mumemto/mum_coverage.py directly.", file=sys.stderr)
            sys.exit(1)
        subprocess.run([sys.executable, script] + args)
        
def run_collinear(args):
    """Run MUM collinear blocking"""
    try:
        collinear = import_module('mumemto.collinear_block')
        parsed_args = collinear.parse_arguments(args)
        collinear.main(parsed_args)
    except ImportError:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        script = os.path.join(script_dir, '_mumemto', 'collinear_block.py')
        if not os.path.exists(script):
            print(f"Error: mumemto not installed. Please run mumemto/collinear_block.py directly.", file=sys.stderr)
            sys.exit(1)
        subprocess.run([sys.executable, script] + args)

def run_convert(args):
    """Convert MUMs to BUMs and vice versa"""
    try:
        convert = import_module('mumemto.mum_to_bumbl')
        parsed_args = convert.parse_arguments(args)
        convert.main(parsed_args)
    except ImportError:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        script = os.path.join(script_dir, '_mumemto', 'mum_to_bumbl.py')
        if not os.path.exists(script):
            print(f"Error: mumemto not installed. Please run mumemto/mum_to_bumbl.py directly.", file=sys.stderr)
            sys.exit(1)
        subprocess.run([sys.executable, script] + args)
        
def run_extract(args):
    """Extract MUMs to a FASTA file"""
    script_dir = os.path.dirname(os.path.abspath(__file__))
    exec_path = os.path.join(script_dir, 'extract_mums')
    if not os.path.exists(exec_path):
        print("Error: mumemto not installed. Please use make to install mumemto first", file=sys.stderr)
        sys.exit(1)
    cmd = [exec_path] + args
    subprocess.run(cmd)
        
def run_label(args):
    """Add contig information to MUMs"""
    try:
        label = import_module('mumemto.get_sequence_info')
        parsed_args = label.parse_arguments(args)
        label.main(parsed_args)
    except ImportError:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        script = os.path.join(script_dir, '_mumemto', 'get_sequence_info.py')
        if not os.path.exists(script):
            print(f"Error: mumemto not installed. Please run mumemto/get_sequence_info.py directly.", file=sys.stderr)
            sys.exit(1)
        subprocess.run([sys.executable, script] + args)

def run_lengths(args):
    """Run the compute_lengths executable with given args"""
    script_dir = os.path.dirname(os.path.abspath(__file__))
    exec_path = os.path.join(script_dir, 'compute_lengths')
    if not os.path.exists(exec_path):
        print("Error: mumemto not installed. Please use make to install mumemto first", file=sys.stderr)
        sys.exit(1)
    cmd = [exec_path] + args
    subprocess.run(cmd)

def run_merge(args):
    """Run the merge executable with given args"""
    try:
        merge = import_module('mumemto.merge_mums')
        parsed_args = merge.parse_arguments(args)
        merge.main(parsed_args)
    except ImportError:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        script = os.path.join(script_dir, '_mumemto', 'merge_mums.py')
        if not os.path.exists(script):
            print(f"Error: mumemto not installed. Please run mumemto/merge_mums.py directly.", file=sys.stderr)
            sys.exit(1)
        subprocess.run([sys.executable, script] + args)
        
def main():
    if len(sys.argv) == 1:
        print("\nmumemto - find maximal [unique | exact] matches using PFP.\n", file=sys.stderr)
        print("Usage: mumemto [subcommand] [ARGS]\nUse -h for detailed usage for each subcommand.", file=sys.stderr)
        print("Commands:\n" +
              "\t[default]\t\tcompute multi-MUMs and MEMS across a collection of sequences\n" +
              "\tviz\t\t\tvisualize multi-MUM synteny\n" +
              "\tcoverage\t\tcompute multi-MUM coverage\n" + 
              "\tinversion\t\tidentify inversion SVs\n" +
              "\tcollinear\t\tfind collinear blocks of MUMs\n" +
              "\tconvert\t\t\tconvert MUMs to BUMs and vice versa\n" +
              "\textract\t\t\textract MUMs to a FASTA file\n" + 
              "\tlabel\t\t\tlabel MUMs with contig information\n" +
              "\tlengths\t\t\trecompute sequence lengths from a filelist\n" +
              "\tmerge\t\t\tmerge MUMs using anchor-based or string-based merging\n",
              file=sys.stderr)
        sys.exit(0)

    command = sys.argv[1]
    args = sys.argv[2:]

    if command == '--version':
        print(f"mumemto version: {MUMEMTO_VERSION}")
        sys.exit(0)
    elif command == 'viz':
        run_viz(args)
    elif command == 'inversion':
        run_inversions(args)
    elif command == 'coverage':
        run_coverage(args)
    elif command == 'collinear':
        run_collinear(args)
    elif command == 'convert':
        run_convert(args)
    elif command == 'extract':
        run_extract(args)
    elif command == 'label':
        run_label(args)
    elif command == 'lengths':
        run_lengths(args)
    elif command == 'merge':
        run_merge(args)
    else:
        # If no special command, pass all args to mumemto executable
        run_mumemto(sys.argv[1:])

if __name__ == '__main__':
    main() 