// bibiman - a TUI for managing BibLaTeX databases
// Copyright (C) 2024  lukeflo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
/////

use dirs::{config_dir, data_dir, home_dir};
use indoc::formatdoc;
use lexopt::prelude::*;
use owo_colors::OwoColorize;
use owo_colors::colors::css::LightGreen;
use owo_colors::colors::*;
use std::env::current_dir;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

use crate::app;
use crate::bibiman::citekeys::CitekeyFormatting;
use crate::config::BibiConfig;

// struct for CLIArgs
#[derive(Debug, Default, Clone)]
pub struct CLIArgs {
    pub pos_args: Vec<PathBuf>,
    pub cfg_path: Option<PathBuf>,
    pub light_theme: bool,
    pub pdf_path: Option<PathBuf>,
    data_path: PathBuf,
    log_file: PathBuf,
    cli_only: bool,
}

impl CLIArgs {
    /// This struct parses the command line and initializes and returns the
    /// necessary structs `CLIArgs` and `BibiConfig`.
    ///
    /// Additionally, it returns a bool which defines if the TUI should be run
    /// or not. The latter is the case for pure CLI processes as `format-citekeys`.
    pub fn parse_args() -> color_eyre::Result<(CLIArgs, BibiConfig, bool)> {
        let mut args = CLIArgs::default();
        let mut parser = lexopt::Parser::from_env();
        let mut subcommand = None;
        let mut run_tui = true;

        // Default config
        args.cfg_path = if config_dir().is_some() {
            Some(config_dir().unwrap().join("bibiman/bibiman.toml"))
        } else if home_dir().is_some() {
            Some(home_dir().unwrap().join(".config/bibiman/bibiman.toml"))
        } else {
            None
        };

        args.data_path = if let Some(dir) = data_dir() {
            dir.join("bibiman")
        } else if let Some(home) = home_dir() {
            home.join(".config/share/bibiman")
        } else {
            current_dir()?
        };

        if !args.data_path.exists() {
            create_dir_all(&args.data_path)?
        }

        args.log_file = args.data_path.join("bibiman.log");

        // if parser
        //     .raw_args()
        //     .is_ok_and(|mut arg| arg.next_if(|a| a == "format-citekeys").is_some())
        // {
        //     todo!("Format citekeys options");
        // }

        while let Some(arg) = parser.next()? {
            match arg {
                Short('h') | Long("help") => {
                    println!("{}", help_func());
                    std::process::exit(0);
                }
                Short('v') | Long("version") => {
                    println!("{}", version_func());
                    std::process::exit(0);
                }
                Short('c') | Long("config-file") => args.cfg_path = Some(parser.value()?.parse()?),
                Short('l') | Long("log-file") => args.log_file = parser.value()?.parse()?,
                Short('C') | Long("cli-only") => args.cli_only = true,
                Long("light-terminal") => args.light_theme = true,
                Long("pdf-path") => {
                    args.pdf_path = Some(parser.value()?.parse()?);
                }
                Value(pos_arg) => {
                    if args.pos_args.is_empty() {
                        let value = pos_arg
                            .into_string()
                            .unwrap_or_else(|os| os.to_string_lossy().to_string());
                        match value.as_str() {
                            "format-citekeys" => {
                                subcommand = Some(value);
                                run_tui = false;
                                break;
                            }
                            _ => {
                                args.pos_args.push(value.into());
                            }
                        }
                    } else {
                        args.pos_args.push(pos_arg.into());
                    }
                }
                _ => return Err(arg.unexpected().into()),
            }
        }

        if args
            .cfg_path
            .as_ref()
            .is_some_and(|f| f.try_exists().is_err() || !f.is_file())
        {
            BibiConfig::create_default_config(&args);
        }

        let mut cfg = if args.cfg_path.is_some() {
            BibiConfig::parse_config(&args)?
        } else {
            BibiConfig::new(&args)
        };

        if let Some(cmd) = subcommand {
            match cmd.as_str() {
                "format-citekeys" => {
                    CitekeyFormatting::parse_citekey_cli(&mut parser, &cfg)?;
                }
                _ => {}
            }
        }

        cfg.cli_overwrite(&args);

        Ok((args, cfg, run_tui))
    }

    pub fn data_path(&self) -> &Path {
        &self.data_path
    }

    pub fn log_file(&self) -> &Path {
        &self.log_file
    }

    pub fn cli_only(&self) -> bool {
        self.cli_only
    }
}

/// This function maps a vector containing paths to another vector containing paths.
/// But it will walk all entries of the first vec which are directories
/// and put only valid file paths with `.bib` ending to the resulting vec.
pub fn parse_files(args: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut files: Vec<PathBuf> = Vec::new();
    // If pos arg is file, just push it to path vec
    for i in args {
        // Expand tilde to /home/user
        let i = if i.starts_with("~") {
            app::expand_home(&i)
        } else {
            i
        };
        if i.is_file() {
            files.push(i);
        // If pos arg is dir, walk dir and collect bibfiles
        } else if i.is_dir() {
            for file in WalkDir::new(i) {
                let f = file.unwrap().into_path();
                if f.is_file()
                    && f.extension().is_some()
                    && f.extension().unwrap_or_default() == "bib"
                {
                    files.push(f)
                }
            }
        } else {
            println!(
                "{}\n{}",
                "The positional argument is neither a valid file, nor a directory:"
                    .red()
                    .bold(),
                i.as_os_str().to_string_lossy().bright_red().italic()
            );
            println!();
            println!("{}", help_func());
            std::process::exit(1)
        }
    }
    files
}

pub fn help_func() -> String {
    let help = vec![
        format!(
            "{} {}\n",
            env!("CARGO_PKG_NAME").fg::<Green>().bold(),
            env!("CARGO_PKG_VERSION").fg::<LightGreen>(),
        ),
        format!(
            "{}\n\t{} [OPTIONS] [SUBCOMMAND | POSITIONAL ARGUMENTS]\n",
            "USAGE".bold(),
            env!("CARGO_PKG_NAME").fg::<White>().bold()
        ),
        formatdoc!(
            "
                \tYou can either use a {} or {}, not both!
            ",
            "subcommand".bold(),
            "positional arguments".bold()
        ),
        format!(
            "{}\n\t{}\t\tPath to {} file",
            "POSITIONAL ARGUMENTS".bold(),
            "<file>".fg::<Magenta>().bold(),
            ".bib".fg::<BrightBlack>().bold()
        ),
        format!(
            "\t{}\tPath to directory containing {} files",
            "<directory>".fg::<BrightBlue>().bold(),
            ".bib".fg::<BrightBlack>().bold()
        ),
        format!("\n\t{}", "Both can be passed multiple times".italic()),
        format!("\n{}", "SUBCOMMANDS".bold()),
        formatdoc!(
            "
                \t{}
                \tRun the citekey formatting procedure on a specified bibfile.
                \tFor further infos run {}
            ",
            "format-citekeys".fg::<BrightYellow>().bold(),
            "bibiman format-citekeys --help".fg::<BrightBlack>().bold()
        ),
        format!("{}", "OPTIONS".bold()),
        formatdoc!(
            "
            \t{}
            \tShow this help and exit
            ",
            "-h, --help".bold().fg::<White>()
        ),
        formatdoc!(
            "
            \t{}
            \tShow the version and exit
            ",
            "-v, --version".bold().fg::<White>()
        ),
        formatdoc!(
            "
            \t{}
            \tEnable default colors for light terminal background
            ",
            "--light-terminal".bold().fg::<White>()
        ),
        formatdoc!(
            "
            \t{}{}
            \tPath to config file used for current session.
            \tTakes precedence over standard config file.
            ",
            "-c, --config-file=".bold().fg::<White>(),
            "<PATH>".bold().italic().fg::<White>()
        ),
        formatdoc!(
            "
            \t{}{}
            \tPath to log file used for current session.
            \tTakes precedence over standard logging path.
            ",
            "-l, --log-file=".bold().fg::<White>(),
            "<PATH>".bold().italic().fg::<White>()
        ),
        formatdoc!(
            "
            \t{}{}
            \tPath to directory containing PDF files.
            \tIf the pdf files basename matches an entrys citekey,
            \tits attached as connected PDF file for the current session.
            \tDoes not edit the bibfile itself!
            ",
            "--pdf-path=".bold().fg::<White>(),
            "<PATH>".bold().italic().fg::<White>()
        ),
        formatdoc!(
            "
            \t{}
            \tLoad only entries from the file(s)/dirs set at the CLI.
            \tIgnores files from the config file
            ",
            "-C, --cli-only".bold().fg::<White>()
        ),
    ];
    let help = help.join("\n");
    help
}

pub fn version_func() -> String {
    let version: Vec<String> = vec![
        format!(
            "{} {}",
            env!("CARGO_PKG_NAME").fg::<Green>().bold(),
            env!("CARGO_PKG_VERSION").fg::<LightGreen>()
        ),
        format!("{}", env!("CARGO_PKG_AUTHORS").bold()),
        format!("{}", env!("CARGO_PKG_LICENSE")),
        format!("\n"),
        format!(
            "{} {}",
            "Target Triple:".bold(),
            env!("TARGET").fg::<BrightRed>()
        ),
    ];
    let version = version.join("\n");
    version
}

pub fn setup_bibiman_logging(args: &CLIArgs) -> color_eyre::Result<()> {
    // simple_logging::log_to_file(args.log_file(), log::LevelFilter::Debug)?;
    let _logger = flexi_logger::Logger::try_with_str("debug")?
        .log_to_file(flexi_logger::FileSpec::try_from(args.log_file())?)
        .write_mode(flexi_logger::WriteMode::BufferAndFlush)
        .start()?;

    Ok(())
}
