import argparse
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import subprocess
import sys


def process_bam(bam_path):
  bam_str = str(bam_path)
  # Generate output filename: e.g., 1.bam -> 1-filtered.bam
  output_bam = str(bam_path.with_name(bam_path.stem + "-filtered.bam"))

  # Construct the pipelined shell command
  cmd = (
      f"samtools view -h {bam_str} | python"
      f" ../filter-BAM-SOI-all-alignments.py"
      f" /mounts/lovelace/temporary/SoI-for-workflow.csv | samtools view -b -o"
      f" {output_bam}"
  )

  print(f"[START] Processing {bam_str} -> {output_bam}")
  try:
    subprocess.run(cmd, shell=True, check=True)
    print(f"[SUCCESS] Finished {bam_str}")
    return True
  except subprocess.CalledProcessError as e:
    print(f"[ERROR] Failed processing {bam_str}: {e}", file=sys.stderr)
    return False


def main():
  parser = argparse.ArgumentParser(
      description=(
          "Run the BAM SOI filtering pipeline in parallel across all BAM"
          " files in the directory."
      )
  )
  parser.add_argument(
      "-n",
      "--numprocs",
      type=int,
      required=True,
      help="Number of concurrent processes to run",
  )
  args = parser.parse_args()

  # Find all .bam files in the current directory, excluding already filtered ones
  current_dir = Path(".")
  bam_files = [
      p for p in current_dir.glob("*.bam") if not p.name.endswith("-filtered.bam")
  ]

  if not bam_files:
    print("[WARNING] No unfiltered .bam files found in the current directory.")
    return

  print(f"Found {len(bam_files)} BAM files to process.")
  print(f"Executing with up to {args.numprocs} parallel processes.\n")

  success_count = 0
  # Execute pipeline tasks in parallel
  with ProcessPoolExecutor(max_workers=args.numprocs) as executor:
    futures = {executor.submit(process_bam, bam): bam for bam in bam_files}
    for future in as_completed(futures):
      if future.result():
        success_count += 1

  print(
      f"\n[SUMMARY] Pipeline complete. {success_count}/{len(bam_files)} files"
      " processed successfully."
  )


if __name__ == "__main__":
  main()