//! Command registry — lookup, indexing, and the canonical command list.

use std::collections::HashMap;

use ftui::{KeyCode, Modifiers};

use crate::message::{InputMode, Screen};

use super::defs::{CommandDef, KeyCombo, ScreenFilter};

// ---------------------------------------------------------------------------
// CommandRegistry
// ---------------------------------------------------------------------------

/// Single source of truth for all TUI commands.
///
/// Built once at startup via [`build_registry`]. Provides O(1) lookup
/// by keybinding and per-screen filtering.
pub struct CommandRegistry {
    pub(crate) commands: Vec<CommandDef>,
    /// Single-key -> command IDs that start with this key.
    by_single_key: HashMap<(KeyCode, Modifiers), Vec<usize>>,
    /// Full sequence -> command index (for two-key combos).
    by_sequence: HashMap<KeyCombo, usize>,
}

impl CommandRegistry {
    /// Look up a command by a single key press on a given screen and input mode.
    ///
    /// Returns `None` if no matching command is found. For sequence starters
    /// (like 'g'), returns `None` — use [`is_sequence_starter`] to detect
    /// that case.
    #[must_use]
    pub fn lookup_key(
        &self,
        code: &KeyCode,
        modifiers: &Modifiers,
        screen: &Screen,
        mode: &InputMode,
    ) -> Option<&CommandDef> {
        let is_text = matches!(mode, InputMode::Text);
        let key = (*code, *modifiers);

        let indices = self.by_single_key.get(&key)?;
        for &idx in indices {
            let cmd = &self.commands[idx];
            if !cmd.available_in.matches(screen) {
                continue;
            }
            if is_text && !cmd.available_in_text_mode {
                continue;
            }
            // Only match Single combos here, not sequence starters.
            if let Some(KeyCombo::Single { .. }) = &cmd.keybinding {
                return Some(cmd);
            }
        }
        None
    }

    /// Complete a two-key sequence.
    ///
    /// Called after the first key of a sequence is detected (e.g., after 'g').
    #[must_use]
    pub fn complete_sequence(
        &self,
        first_code: &KeyCode,
        first_modifiers: &Modifiers,
        second_code: &KeyCode,
        second_modifiers: &Modifiers,
        screen: &Screen,
    ) -> Option<&CommandDef> {
        let combo = KeyCombo::Sequence {
            first_code: *first_code,
            first_modifiers: *first_modifiers,
            second_code: *second_code,
            second_modifiers: *second_modifiers,
        };
        let &idx = self.by_sequence.get(&combo)?;
        let cmd = &self.commands[idx];
        if cmd.available_in.matches(screen) {
            Some(cmd)
        } else {
            None
        }
    }

    /// Whether a key starts a multi-key sequence (e.g., 'g').
    #[must_use]
    pub fn is_sequence_starter(&self, code: &KeyCode, modifiers: &Modifiers) -> bool {
        self.by_sequence
            .keys()
            .any(|combo| combo.starts_with(code, modifiers))
    }

    /// Commands available for the command palette on a given screen.
    ///
    /// Returned sorted by label.
    #[must_use]
    pub fn palette_entries(&self, screen: &Screen) -> Vec<&CommandDef> {
        let mut entries: Vec<&CommandDef> = self
            .commands
            .iter()
            .filter(|c| c.available_in.matches(screen))
            .collect();
        entries.sort_by_key(|c| c.label);
        entries
    }

    /// Commands for the help overlay on a given screen.
    #[must_use]
    pub fn help_entries(&self, screen: &Screen) -> Vec<&CommandDef> {
        self.commands
            .iter()
            .filter(|c| c.available_in.matches(screen))
            .filter(|c| c.keybinding.is_some())
            .collect()
    }

    /// Status bar hints for the current screen.
    #[must_use]
    pub fn status_hints(&self, screen: &Screen) -> Vec<&str> {
        self.commands
            .iter()
            .filter(|c| c.available_in.matches(screen))
            .filter(|c| !c.status_hint.is_empty())
            .map(|c| c.status_hint)
            .collect()
    }

    /// Total number of registered commands.
    #[must_use]
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Whether the registry has no commands.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }
}

// ---------------------------------------------------------------------------
// build_registry
// ---------------------------------------------------------------------------

/// Build the command registry with all TUI commands.
///
/// This is the single source of truth — every keybinding, help text,
/// and palette entry originates here.
#[must_use]
pub fn build_registry() -> CommandRegistry {
    let commands = vec![
        // --- Global commands ---
        CommandDef {
            id: "quit",
            label: "Quit",
            keybinding: Some(KeyCombo::key(KeyCode::Char('q'))),
            cli_equivalent: None,
            help_text: "Exit the TUI",
            status_hint: "q:quit",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_back",
            label: "Go Back",
            keybinding: Some(KeyCombo::key(KeyCode::Escape)),
            cli_equivalent: None,
            help_text: "Go back to previous screen",
            status_hint: "esc:back",
            available_in: ScreenFilter::Global,
            available_in_text_mode: true,
        },
        CommandDef {
            id: "show_help",
            label: "Help",
            keybinding: Some(KeyCombo::key(KeyCode::Char('?'))),
            cli_equivalent: None,
            help_text: "Show keybinding help overlay",
            status_hint: "?:help",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "command_palette",
            label: "Command Palette",
            keybinding: Some(KeyCombo::ctrl(KeyCode::Char('p'))),
            cli_equivalent: None,
            help_text: "Open command palette",
            status_hint: "C-p:palette",
            available_in: ScreenFilter::Global,
            available_in_text_mode: true,
        },
        CommandDef {
            id: "open_in_browser",
            label: "Open in Browser",
            keybinding: Some(KeyCombo::key(KeyCode::Char('o'))),
            cli_equivalent: None,
            help_text: "Open current entity in browser",
            status_hint: "o:browser",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "show_cli",
            label: "Show CLI Equivalent",
            keybinding: Some(KeyCombo::key(KeyCode::Char('!'))),
            cli_equivalent: None,
            help_text: "Show equivalent lore CLI command",
            status_hint: "",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "toggle_scope",
            label: "Project Scope",
            keybinding: Some(KeyCombo::key(KeyCode::Char('P'))),
            cli_equivalent: None,
            help_text: "Toggle project scope filter",
            status_hint: "P:scope",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        // --- Navigation: g-prefix sequences ---
        CommandDef {
            id: "go_home",
            label: "Go to Dashboard",
            keybinding: Some(KeyCombo::g_then('h')),
            cli_equivalent: None,
            help_text: "Jump to dashboard",
            status_hint: "gh:home",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_issues",
            label: "Go to Issues",
            keybinding: Some(KeyCombo::g_then('i')),
            cli_equivalent: Some("lore issues"),
            help_text: "Jump to issue list",
            status_hint: "gi:issues",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_mrs",
            label: "Go to Merge Requests",
            keybinding: Some(KeyCombo::g_then('m')),
            cli_equivalent: Some("lore mrs"),
            help_text: "Jump to MR list",
            status_hint: "gm:mrs",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_search",
            label: "Go to Search",
            keybinding: Some(KeyCombo::g_then('/')),
            cli_equivalent: Some("lore search"),
            help_text: "Jump to search",
            status_hint: "g/:search",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_timeline",
            label: "Go to Timeline",
            keybinding: Some(KeyCombo::g_then('t')),
            cli_equivalent: Some("lore timeline"),
            help_text: "Jump to timeline",
            status_hint: "gt:timeline",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_who",
            label: "Go to Who",
            keybinding: Some(KeyCombo::g_then('w')),
            cli_equivalent: Some("lore who"),
            help_text: "Jump to people intelligence",
            status_hint: "gw:who",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_sync",
            label: "Go to Sync",
            keybinding: Some(KeyCombo::g_then('s')),
            cli_equivalent: Some("lore sync"),
            help_text: "Jump to sync status",
            status_hint: "gs:sync",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_file_history",
            label: "Go to File History",
            keybinding: Some(KeyCombo::g_then('f')),
            cli_equivalent: Some("lore file-history"),
            help_text: "Jump to file history",
            status_hint: "gf:files",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_trace",
            label: "Go to Trace",
            keybinding: Some(KeyCombo::g_then('r')),
            cli_equivalent: Some("lore trace"),
            help_text: "Jump to trace",
            status_hint: "gr:trace",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_doctor",
            label: "Go to Doctor",
            keybinding: Some(KeyCombo::g_then('d')),
            cli_equivalent: Some("lore doctor"),
            help_text: "Jump to environment health checks",
            status_hint: "gd:doctor",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "go_stats",
            label: "Go to Stats",
            keybinding: Some(KeyCombo::g_then('x')),
            cli_equivalent: Some("lore stats"),
            help_text: "Jump to database statistics",
            status_hint: "gx:stats",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        // --- Vim-style jump list ---
        CommandDef {
            id: "jump_back",
            label: "Jump Back",
            keybinding: Some(KeyCombo::ctrl(KeyCode::Char('o'))),
            cli_equivalent: None,
            help_text: "Jump backward through visited detail views",
            status_hint: "C-o:jump back",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        CommandDef {
            id: "jump_forward",
            label: "Jump Forward",
            keybinding: Some(KeyCombo::ctrl(KeyCode::Char('i'))),
            cli_equivalent: None,
            help_text: "Jump forward through visited detail views",
            status_hint: "",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
        // --- List navigation ---
        CommandDef {
            id: "move_down",
            label: "Move Down",
            keybinding: Some(KeyCombo::key(KeyCode::Char('j'))),
            cli_equivalent: None,
            help_text: "Move cursor down",
            status_hint: "j:down",
            available_in: ScreenFilter::Only(vec![
                Screen::IssueList,
                Screen::MrList,
                Screen::Search,
                Screen::Timeline,
            ]),
            available_in_text_mode: false,
        },
        CommandDef {
            id: "move_up",
            label: "Move Up",
            keybinding: Some(KeyCombo::key(KeyCode::Char('k'))),
            cli_equivalent: None,
            help_text: "Move cursor up",
            status_hint: "k:up",
            available_in: ScreenFilter::Only(vec![
                Screen::IssueList,
                Screen::MrList,
                Screen::Search,
                Screen::Timeline,
            ]),
            available_in_text_mode: false,
        },
        CommandDef {
            id: "select_item",
            label: "Select",
            keybinding: Some(KeyCombo::key(KeyCode::Enter)),
            cli_equivalent: None,
            help_text: "Open selected item",
            status_hint: "enter:open",
            available_in: ScreenFilter::Only(vec![
                Screen::IssueList,
                Screen::MrList,
                Screen::Search,
            ]),
            available_in_text_mode: false,
        },
        // --- Filter ---
        CommandDef {
            id: "focus_filter",
            label: "Filter",
            keybinding: Some(KeyCombo::key(KeyCode::Char('/'))),
            cli_equivalent: None,
            help_text: "Focus the filter input",
            status_hint: "/:filter",
            available_in: ScreenFilter::Only(vec![Screen::IssueList, Screen::MrList]),
            available_in_text_mode: false,
        },
        // --- Scroll ---
        CommandDef {
            id: "scroll_to_top",
            label: "Scroll to Top",
            keybinding: Some(KeyCombo::g_then('g')),
            cli_equivalent: None,
            help_text: "Scroll to the top of the current view",
            status_hint: "",
            available_in: ScreenFilter::Global,
            available_in_text_mode: false,
        },
    ];

    build_from_defs(commands)
}

/// Build index maps from a list of command definitions.
fn build_from_defs(commands: Vec<CommandDef>) -> CommandRegistry {
    let mut by_single_key: HashMap<(KeyCode, Modifiers), Vec<usize>> = HashMap::new();
    let mut by_sequence: HashMap<KeyCombo, usize> = HashMap::new();

    for (idx, cmd) in commands.iter().enumerate() {
        if let Some(combo) = &cmd.keybinding {
            match combo {
                KeyCombo::Single { code, modifiers } => {
                    by_single_key
                        .entry((*code, *modifiers))
                        .or_default()
                        .push(idx);
                }
                KeyCombo::Sequence { .. } => {
                    by_sequence.insert(combo.clone(), idx);
                    // Also index the first key so is_sequence_starter works via by_single_key.
                    if let KeyCombo::Sequence {
                        first_code,
                        first_modifiers,
                        ..
                    } = combo
                    {
                        by_single_key
                            .entry((*first_code, *first_modifiers))
                            .or_default()
                            .push(idx);
                    }
                }
            }
        }
    }

    CommandRegistry {
        commands,
        by_single_key,
        by_sequence,
    }
}
