toolkitrs 0.1.13

A unified FFmpeg workflow CLI for batch media conversion, remuxing, and thumbnail embedding
//! module github::tui - TUI integration for the GitHub contributions exporter.
//!
//! Text options follow the "placeholder is the default" convention: the TUI
//! stores whatever the inline editor displays when the user accepts it without
//! typing. That makes `since` default to `yesterday` and `until` default to
//! `today`; the keywords are resolved by `github::config` for CLI and TUI alike.

use crate::{
    github,
    tui::{
        app::RunOptions,
        command::{CommandOption, FilePickerMode, TuiCommand},
        event::AppEvent,
    },
};
use anyhow::Result;
use std::{
    path::{Path, PathBuf},
    sync::mpsc::Sender,
};
use tokio_util::sync::CancellationToken;

// ------------------------------------------ Types & Impls ------------------------------------- //

/// The gh-contrib command as a TUI-executable workflow.
#[derive(Debug)]
pub struct GhContribCommand;
impl TuiCommand for GhContribCommand {
    /// Stable identifier for this command.
    fn id(&self) -> &'static str {
        "gh-contrib"
    }

    /// Short title shown in the home list.
    fn title(&self) -> &'static str {
        "gh-contrib"
    }

    /// One-line description shown next to the title.
    fn description(&self) -> &'static str {
        "Export GitHub commits to a text file"
    }

    /// gh-contrib fetches from the GitHub API, so no file picker is needed.
    fn file_picker_mode(&self) -> FilePickerMode {
        FilePickerMode::NotNeeded
    }

    /// Configurable options shown on the options screen.
    ///
    /// NOTE: for `Text` options the placeholder doubles as the default value:
    /// accepting the editor without typing stores exactly what was displayed.
    fn options(&self) -> Vec<CommandOption> {
        vec![
            CommandOption::Text {
                label: "GitHub username",
                default: "",
                placeholder: "",
            },
            CommandOption::Text {
                label: "Since (YYYY-MM-DD)",
                default: "yesterday",
                placeholder: "yesterday",
            },
            CommandOption::Text {
                label: "Until (YYYY-MM-DD)",
                default: "today",
                placeholder: "today",
            },
            CommandOption::Toggle {
                label: "Skip README files",
                default: false,
            },
        ]
    }

    /// Runs the gh-contrib workflow, streaming all progress through `tx`
    /// so the TUI renderer stays the sole owner of the terminal.
    fn execute(
        &self,
        _files: Vec<PathBuf>, // unused โ€” no file picker
        options: &RunOptions,
        cancel: CancellationToken,
        _ffmpeg_path: &Path, // unused โ€” not a media command
        tx: Sender<AppEvent>,
    ) -> Result<()> {
        let username = options
            .custom
            .get("GitHub username")
            .cloned()
            .unwrap_or_default();
        let since = options
            .custom
            .get("Since (YYYY-MM-DD)")
            .cloned()
            .unwrap_or_default();
        let until = options
            .custom
            .get("Until (YYYY-MM-DD)")
            .cloned()
            .unwrap_or_default();
        let no_readme = options
            .custom
            .get("Skip README files")
            .map(|v| v == "true")
            .unwrap_or(false);

        if username.is_empty() || since.is_empty() || until.is_empty() {
            let _ = tx.send(AppEvent::Log("ERROR: missing username or dates".into()));
            let _ = tx.send(AppEvent::AllDone {
                succeeded: 0,
                failed: 1,
            });
            return Ok(());
        }

        // `new_config` resolves `today` / `yesterday` for us.
        let cfg = match github::config::new_config(&username, &since, &until, !no_readme) {
            Ok(c) => c,
            Err(e) => {
                let _ = tx.send(AppEvent::Log(format!("ERROR: {e}")));
                let _ = tx.send(AppEvent::AllDone {
                    succeeded: 0,
                    failed: 1,
                });
                return Ok(());
            }
        };

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()?;
        runtime.block_on(async {
            if cancel.is_cancelled() {
                return;
            }
            let _ = tx.send(AppEvent::Log("Fetching repositories...".into()));

            // Wrap initial fetch in select! for instant TUI response.
            let repos = tokio::select! {
                _ = cancel.cancelled() => {
                    let _ = tx.send(AppEvent::Log("Cancelled".into()));
                    let _ = tx.send(AppEvent::AllDone { succeeded: 0, failed: 0 });
                    return;
                }
                res = github::api::fetch_repositories(&cfg) => match res {
                    Ok(r) => r,
                    Err(e) => {
                        let _ = tx.send(AppEvent::Log(format!("ERROR: {e}")));
                        let _ = tx.send(AppEvent::AllDone { succeeded: 0, failed: 1 });
                        return;
                    }
                }
            };

            let _ = tx.send(AppEvent::Log(format!("Found {} repositories", repos.len())));
            if cancel.is_cancelled() {
                let _ = tx.send(AppEvent::Log("Cancelled".into()));
                let _ = tx.send(AppEvent::AllDone {
                    succeeded: 0,
                    failed: 0,
                });
                return;
            }

            let output_file = PathBuf::from(github::types::output_filename(
                &cfg.username,
                &cfg.since,
                &cfg.until,
            ));
            let file_writer = match github::writer::SafeFileWriter::new(&output_file) {
                Ok(w) => std::sync::Arc::new(w),
                Err(e) => {
                    let _ = tx.send(AppEvent::Log(format!("ERROR: {e}")));
                    let _ = tx.send(AppEvent::AllDone {
                        succeeded: 0,
                        failed: 1,
                    });
                    return;
                }
            };
            file_writer.write_header(&cfg.username, &cfg.since, &cfg.until);

            // ๐Ÿงต Progress logger for the pool: forwards into the TUI event
            // channel instead of stderr. Direct terminal writes would corrupt
            // the alternate-screen frame.
            let log_tx = tx.clone();
            let progress_log = move |line: &str| {
                let _ = log_tx.send(AppEvent::Log(line.to_string()));
            };

            // ๐Ÿ“ฆ Pass the cancellation token (and the TUI-safe logger) down.
            let (total_commits, repo_count) = github::processor::process_repositories(
                &cfg,
                &repos,
                &file_writer,
                cancel.clone(),
                progress_log,
            )
            .await;

            if cancel.is_cancelled() {
                let _ = tx.send(AppEvent::Log(
                    "Cancelled by user. Output may be incomplete.".into(),
                ));
                let _ = tx.send(AppEvent::AllDone {
                    succeeded: 0,
                    failed: 0,
                });
                return;
            }

            file_writer.write_summary(total_commits, repo_count);
            let _ = tx.send(AppEvent::Log(format!(
                "Done! Output: {}",
                output_file.display()
            )));
            let _ = tx.send(AppEvent::AllDone {
                succeeded: 1,
                failed: 0,
            });
        });
        Ok(())
    }
}