"""
Vim/Neovim Integration

Provides configuration for Vim and Neovim editors.
"""

import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from groknroll.ide.base import IDEConfig, IDEType, IntegrationResult

logger = logging.getLogger(__name__)


@dataclass
class VimConfig:
    """Vim specific configuration"""

    mappings: dict[str, str] = field(default_factory=dict)
    commands: list[str] = field(default_factory=list)
    settings: dict[str, Any] = field(default_factory=dict)


@dataclass
class NeovimConfig:
    """Neovim specific configuration (Lua-based)"""

    mappings: dict[str, str] = field(default_factory=dict)
    commands: list[str] = field(default_factory=list)
    settings: dict[str, Any] = field(default_factory=dict)


def generate_vim_config(config: IDEConfig) -> str:
    """Generate Vim configuration"""
    cmd = config.groknroll_path or "groknroll"
    return f"""" groknroll.vim - Vim integration for groknroll
" Add to your .vimrc: source ~/.vim/groknroll.vim

" Commands
command! GroknrollTUI execute '!{cmd}'
command! GroknrollBuild execute '!{cmd} build'
command! GroknrollPlan execute '!{cmd} build --agent plan'
command! GroknrollOracle execute '!{cmd} oracle'
command! GroknrollAnalyze execute '!{cmd} analyze %'
command! GroknrollReview execute '!{cmd} review %'

" Mappings (Leader key defaults to \\)
nnoremap <leader>gt :GroknrollTUI<CR>
nnoremap <leader>gb :GroknrollBuild<CR>
nnoremap <leader>gp :GroknrollPlan<CR>
nnoremap <leader>go :GroknrollOracle<CR>
nnoremap <leader>ga :GroknrollAnalyze<CR>
nnoremap <leader>gr :GroknrollReview<CR>

" Terminal integration (Vim 8+)
if has('terminal')
  command! GroknrollTerminal terminal {cmd}
  nnoremap <leader>gT :GroknrollTerminal<CR>
endif
"""


def generate_neovim_config(config: IDEConfig) -> str:
    """Generate Neovim Lua configuration"""
    cmd = config.groknroll_path or "groknroll"
    return f'''-- groknroll.lua - Neovim integration for groknroll
-- Add to your init.lua: require("groknroll")

local M = {{}}

M.cmd = "{cmd}"

-- Run groknroll command in terminal
function M.run(args)
  vim.cmd("terminal " .. M.cmd .. " " .. (args or ""))
end

-- Commands
vim.api.nvim_create_user_command("GroknrollTUI", function() M.run("") end, {{}})
vim.api.nvim_create_user_command("GroknrollBuild", function() M.run("build") end, {{}})
vim.api.nvim_create_user_command("GroknrollPlan", function() M.run("build --agent plan") end, {{}})
vim.api.nvim_create_user_command("GroknrollOracle", function() M.run("oracle") end, {{}})
vim.api.nvim_create_user_command("GroknrollAnalyze", function()
  M.run("analyze " .. vim.fn.expand("%:p"))
end, {{}})
vim.api.nvim_create_user_command("GroknrollReview", function()
  M.run("review " .. vim.fn.expand("%:p"))
end, {{}})

-- Keymaps
local opts = {{ noremap = true, silent = true }}
vim.keymap.set("n", "<leader>gt", ":GroknrollTUI<CR>", opts)
vim.keymap.set("n", "<leader>gb", ":GroknrollBuild<CR>", opts)
vim.keymap.set("n", "<leader>gp", ":GroknrollPlan<CR>", opts)
vim.keymap.set("n", "<leader>go", ":GroknrollOracle<CR>", opts)
vim.keymap.set("n", "<leader>ga", ":GroknrollAnalyze<CR>", opts)
vim.keymap.set("n", "<leader>gr", ":GroknrollReview<CR>", opts)

return M
'''


def setup_vim_integration(config: IDEConfig, **kwargs) -> IntegrationResult:
    """Setup Vim integration"""
    vim_dir = Path.home() / ".vim"
    vim_dir.mkdir(exist_ok=True)
    files_created = []

    try:
        config_file = vim_dir / "groknroll.vim"
        config_file.write_text(generate_vim_config(config))
        files_created.append(config_file)

        return IntegrationResult(
            success=True,
            ide_type=IDEType.VIM,
            files_created=files_created,
            message=f"Vim integration created at {config_file}. Add 'source ~/.vim/groknroll.vim' to .vimrc",
        )
    except Exception as e:
        return IntegrationResult(success=False, ide_type=IDEType.VIM, error=str(e))


def setup_neovim_integration(config: IDEConfig, **kwargs) -> IntegrationResult:
    """Setup Neovim integration"""
    nvim_dir = Path.home() / ".config" / "nvim" / "lua"
    nvim_dir.mkdir(parents=True, exist_ok=True)
    files_created = []

    try:
        config_file = nvim_dir / "groknroll.lua"
        config_file.write_text(generate_neovim_config(config))
        files_created.append(config_file)

        return IntegrationResult(
            success=True,
            ide_type=IDEType.NEOVIM,
            files_created=files_created,
            message=f"Neovim integration created at {config_file}. Add 'require(\"groknroll\")' to init.lua",
        )
    except Exception as e:
        return IntegrationResult(success=False, ide_type=IDEType.NEOVIM, error=str(e))
