use std::io;
use std::num::NonZeroUsize;

use simd_csv::ByteRecord;

use crate::CliResult;
use crate::cmd::parallel::Args as ParallelArgs;
use crate::collections::new_index_set;
use crate::config::{Config, Delimiter};
use crate::select::SelectedColumns;
use crate::util;

static USAGE: &str = "
Concatenates CSV data by column or by row.

When concatenating by column, the columns will be written in the same order as
the inputs given. The number of rows in the result is always equivalent to to
the minimum number of rows across all given CSV data. (This behavior can be
reversed with the '--pad' flag.)

When concatenating by row, all CSV data must have the same number of columns.
If you need to rearrange the columns or fix the lengths of records, use the
'select' or 'fixlengths' commands. Also, only the headers of the *first* CSV
data given are used. Headers in subsequent inputs are ignored. (This behavior
can be disabled with --no-headers.)

Alternatively, you can reorder columns and pad rows using -I/--intersection
or -U/-union. This can be useful when dealing with multiple files having similar
but not exactly identical schemas.

When concatenating a large number of CSV files exceeding your shell's
command arguments limit, prefer using the --paths flag to read the list of CSV
files to concatenate from input lines or from a CSV file containing paths in a
column given to the --path-column flag.

Feeding --paths lines:

    $ xan cat rows --paths paths.txt > concatenated.csv

Feeding --paths CSV file:

    $ xan cat rows --paths files.csv --path-column path > concatenated.csv

Feeding stdin (\"-\") to --paths:

    $ find . -name '*.csv' | xan cat rows --paths - > concatenated.csv

Feeding CSV as stdin (\"-\") to --paths:

    $ cat filelist.csv | xan cat rows --paths - --path-column path > concatenated.csv

You can also use the --glob flag to feed the command a glob pattern (for instance
if your shell does not support it natively or if the number of files exceeds the
arguments limit):

    $ xan cat rows --glob '*.csv' > concatenated.csv

Usage:
    xan cat rows [options] [<inputs>...]
    xan cat (cols|columns) [options] [<inputs>...]
    xan cat --help

cat cols/columns options:
    -p, --pad                   When concatenating columns, this flag will cause
                                all records to appear. It will pad each row if
                                other CSV data isn't long enough.

cat rows options:
    -I, --intersection           Compute the intersection of headers of all concatenated files
                                 and reorder columns of concatenated files accordingly. This is incompatible
                                 with -U/--union, preprocessing and -n/--no-headers.
    -U, --union                  Compute the union of headers of all concatenated files
                                 and reorder columns of concatenated files accordingly. This is incompatible
                                 with -I/--intersection, preprocessing and -n/--no-headers.
    --paths <input>              When concatenating rows, give a text file (use \"-\" for stdin)
                                 containing one path of CSV file to concatenate per line.
    --path-column <name>         When given a column name, --paths will be considered as CSV, and paths
                                 to CSV files to concatenate will be extracted from the selected column.
    --glob <pattern>             Use given glob <pattern> to collect files to concatenate.
    -S, --source-column <name>   Name of a column to prepend in the output of \"cat rows\"
                                 indicating the path to source file.
    -P, --preprocess <op>        Preprocessing using only `xan` subcommands.
                                 See `xan parallel -h` for more information about preprocessing.
    --run <path>                 Run xan script at given <path> as preprocessing.
                                 See `xan run -h` for more information.
    -H, --shell-preprocess <op>  Preprocessing commands that will run directly in your
                                 own shell using the -c flag.
                                 See `xan parallel -h` for more information about preprocessing.
    --raw                        Concatenate files as fast as possible, while skipping subsequent
                                 files' headers. Will not normalize the CSV stream at all while doing
                                 so, nor verify columns alignment. Only use for performance, and
                                 if you know what you are doing.

Common options:
    -h, --help             Display this message
    -o, --output <file>    Write output to <file> instead of stdout.
    -n, --no-headers       When set, the first row will NOT be interpreted
                           as column names. Note that this has no effect when
                           concatenating columns.
    -d, --delimiter <arg>  The field delimiter for reading CSV data.
                           Must be a single character.
";

#[derive(Deserialize)]
struct Args {
    cmd_rows: bool,
    cmd_columns: bool,
    cmd_cols: bool,
    arg_inputs: Vec<String>,
    flag_paths: Option<String>,
    flag_path_column: Option<SelectedColumns>,
    flag_glob: Option<String>,
    flag_pad: bool,
    flag_output: Option<String>,
    flag_no_headers: bool,
    flag_delimiter: Option<Delimiter>,
    flag_source_column: Option<String>,
    flag_raw: bool,
    flag_preprocess: Option<String>,
    flag_shell_preprocess: Option<String>,
    flag_run: Option<String>,
    flag_intersection: bool,
    flag_union: bool,
}

pub fn run(argv: &[&str]) -> CliResult<()> {
    let args: Args = util::get_args(USAGE, argv)?;

    if args.flag_paths.is_some() && !args.arg_inputs.is_empty() {
        Err("--paths cannot be used with other positional arguments!")?;
    }

    if args.flag_intersection && args.flag_union {
        Err("only one of -I/--intersection or -U/--union must be selected!")?;
    }

    if (args.flag_intersection || args.flag_union) && args.flag_no_headers {
        Err("-I/--intersection or -U/--union cannot work with -n/--no-headers!")?;
    }

    if args.flag_preprocess.is_some()
        || args.flag_shell_preprocess.is_some()
        || args.flag_run.is_some()
    {
        if args.flag_intersection || args.flag_union {
            Err("preprocessing is incompatible with -I/--intersection or -U/--union!")?;
        }

        let mut parallel_args = ParallelArgs::default();
        parallel_args.cmd_cat = true;
        parallel_args.arg_inputs = args.paths()?.collect::<Result<Vec<_>, _>>()?;
        parallel_args.flag_source_column = args.flag_source_column;
        parallel_args.flag_preprocess = args.flag_preprocess;
        parallel_args.flag_run = args.flag_run;
        parallel_args.flag_shell_preprocess = args.flag_shell_preprocess;
        parallel_args.flag_no_headers = args.flag_no_headers;
        parallel_args.flag_delimiter = args.flag_delimiter;
        parallel_args.flag_threads = Some(NonZeroUsize::new(1).unwrap());

        return parallel_args.run();
    }

    if args.cmd_rows {
        if args.flag_raw {
            args.cat_rows_raw()
        } else if args.flag_intersection || args.flag_union {
            args.cat_rows_recombobulated()
        } else {
            args.cat_rows()
        }
    } else if args.cmd_columns || args.cmd_cols {
        if args.flag_raw {
            Err("--raw only works with `xan cat rows`!")?;
        }

        args.cat_columns()
    } else {
        unreachable!();
    }
}

impl Args {
    fn paths(&self) -> CliResult<Box<dyn Iterator<Item = CliResult<String>>>> {
        let modes = self.flag_paths.is_some() as u8
            + !self.arg_inputs.is_empty() as u8
            + self.flag_glob.is_some() as u8;

        if modes > 1 {
            Err(
                "this command either accepts arguments or --paths or --glob but not a combination of those!",
            )?;
        }

        if let Some(paths_path) = self.flag_paths.as_ref() {
            Config::new(&Some(paths_path.clone())).lines(&self.flag_path_column)
        } else if let Some(pattern) = self.flag_glob.as_ref() {
            Ok(Box::new(glob::glob(pattern)?.map(|result| {
                Ok(result.unwrap().to_string_lossy().into_owned())
            })))
        } else {
            Ok(Box::new(self.arg_inputs.clone().into_iter().map(Ok)))
        }
    }

    fn cat_rows_raw(&self) -> CliResult<()> {
        let configs = self
            .paths()?
            .map(|p| -> CliResult<Config> {
                Ok(Config::new(&Some(p?))
                    .delimiter(self.flag_delimiter)
                    .no_headers(self.flag_no_headers))
            })
            .collect::<Result<Vec<_>, _>>()?;

        let wconf = Config::new(&self.flag_output);
        let mut writer = wconf.io_writer()?;

        if matches!(configs.first(), Some(c) if c.no_headers) {
            for conf in configs {
                io::copy(&mut conf.io_reader()?, &mut writer)?;
            }
        } else {
            let mut headers_written = false;

            for conf in configs {
                let mut peeker = conf.simd_peeker()?;

                if !headers_written {
                    let mut writer_builder = wconf.simd_csv_writer_builder();
                    writer_builder.crlf_newlines(peeker.has_crlf_newlines()?);

                    let mut csv_writer = wconf.simd_csv_writer_from_writer(&mut writer);

                    csv_writer.write_splitted_record(peeker.peek()?)?;
                    csv_writer.flush()?;

                    headers_written = true;
                }

                io::copy(&mut peeker.into_reader(), &mut writer)?;
            }
        }

        Ok(writer.flush()?)
    }

    fn cat_rows(&self) -> CliResult<()> {
        let mut record = ByteRecord::new();
        let mut wtr = Config::new(&self.flag_output).simd_writer()?;

        let mut headers_opt: Option<ByteRecord> = None;

        for result in self.paths()? {
            let path = result?;

            let mut reader = Config::new(&Some(path.clone()))
                .delimiter(self.flag_delimiter)
                .no_headers(self.flag_no_headers)
                .simd_reader()?;

            if reader.has_headers() {
                match &headers_opt {
                    Some(headers) => {
                        let current_headers = reader.byte_headers()?;

                        if current_headers != headers {
                            Err(format!(
                                "found inconsistent headers as soon as \"{}\"!\nExpected: {:?}\nGot: {:?}",
                                path, headers, current_headers
                            ))?;
                        }
                    }
                    None => {
                        let current_headers = reader.byte_headers()?;

                        headers_opt = Some(current_headers.clone());

                        if let Some(source_column) = &self.flag_source_column {
                            wtr.write_record(
                                [source_column.as_bytes()]
                                    .into_iter()
                                    .chain(current_headers.iter()),
                            )?;
                        } else {
                            wtr.write_byte_record(current_headers)?;
                        }
                    }
                }
            } else {
                match &headers_opt {
                    Some(headers) => {
                        let current_headers = reader.byte_headers()?;

                        if headers.len() != current_headers.len() {
                            Err(format!(
                                "found inconsistent column count as soon as \"{}\"!\nExpected: {}\nGot: {}",
                                path,
                                headers.len(),
                                current_headers.len()
                            ))?;
                        }
                    }
                    None => {
                        headers_opt = Some(reader.byte_headers()?.clone());
                    }
                }
            }

            if self.flag_source_column.is_none() {
                while reader.read_byte_record(&mut record)? {
                    wtr.write_byte_record(&record)?;
                }
            } else {
                while reader.read_byte_record(&mut record)? {
                    wtr.write_record([path.as_bytes()].into_iter().chain(&record))?;
                }
            }
        }

        Ok(wtr.flush()?)
    }

    fn cat_rows_recombobulated(&self) -> CliResult<()> {
        let mut record = ByteRecord::new();
        let mut wtr = Config::new(&self.flag_output).simd_writer()?;

        let mut readers = self
            .paths()?
            .map(
                |p| -> CliResult<simd_csv::Reader<Box<dyn io::Read + Send>>> {
                    Config::new(&Some(p?))
                        .delimiter(self.flag_delimiter)
                        .no_headers(self.flag_no_headers)
                        .simd_reader()
                },
            )
            .collect::<Result<Vec<_>, _>>()?;

        let all_headers = readers
            .iter_mut()
            .map(|reader| reader.byte_headers().cloned())
            .collect::<Result<Vec<_>, _>>()?;

        let mut headers_index = new_index_set::<Vec<u8>>();

        for (i, headers) in all_headers.iter().enumerate() {
            for name in headers {
                if self.flag_intersection {
                    if i == 0 {
                        headers_index.insert(name.to_vec());
                    } else if !headers_index.contains(name) {
                        headers_index.shift_remove(name);
                    }
                } else {
                    headers_index.insert(name.to_vec());
                }
            }
        }

        if headers_index.is_empty() {
            Err(
                "concatenated files have no intersecting headers at all (when using -I/--intersection)!",
            )?;
        }

        let masks = all_headers
            .iter()
            .map(|headers| {
                headers_index
                    .iter()
                    .map(|name| headers.iter().position(|n| name == n))
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();

        wtr.write_record(headers_index.iter())?;

        for (mask, reader) in masks.into_iter().zip(readers.iter_mut()) {
            while reader.read_byte_record(&mut record)? {
                wtr.write_record(mask.iter().map(|i_opt| match i_opt {
                    None => b"",
                    Some(i) => &record[*i],
                }))?;
            }
        }

        Ok(wtr.flush()?)
    }

    fn cat_columns(&self) -> CliResult<()> {
        let mut wtr = Config::new(&self.flag_output).simd_writer()?;

        let mut rdrs = self
            .paths()?
            .map(|p| -> CliResult<_> {
                Config::new(&Some(p?))
                    .delimiter(self.flag_delimiter)
                    .no_headers(true) // NOTE: header info is irrelevant for this operation
                    .simd_reader()
            })
            .collect::<Result<Vec<_>, _>>()?;

        // Find the lengths of each record. If a length varies, then an error
        // will occur so we can rely on the first length being the correct one.
        let mut lengths = vec![];

        for rdr in &mut rdrs {
            lengths.push(rdr.byte_headers()?.len());
        }

        let mut iters = rdrs
            .iter_mut()
            .map(|rdr| rdr.byte_records())
            .collect::<Vec<_>>();

        'OUTER: loop {
            let mut record = ByteRecord::new();
            let mut num_done = 0;
            for (iter, &len) in iters.iter_mut().zip(lengths.iter()) {
                match iter.next() {
                    None => {
                        num_done += 1;
                        if self.flag_pad {
                            for _ in 0..len {
                                record.push_field(b"");
                            }
                        } else {
                            break 'OUTER;
                        }
                    }
                    Some(Err(err)) => Err(err)?,
                    Some(Ok(next)) => record.extend(&next),
                }
            }
            // Only needed when `--pad` is set.
            // When not set, the OUTER loop breaks when the shortest iterator
            // is exhausted.
            if num_done >= iters.len() {
                break 'OUTER;
            }
            wtr.write_byte_record(&record)?;
        }
        wtr.flush().map_err(From::from)
    }
}
