import cmd
import os
import sys
from slack_bot.obsidian.indexer import ObsidianIndexer
from slack_bot.obsidian.indexer import ObsidianIndexer
from slack_bot.obsidian.generators import WritingAssistant, ReplyGenerator, DecisionSupport, SearchAnalyzer
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

class ObsidianShell(cmd.Cmd):
    intro = 'Welcome to the Obsidian Assistant Shell. Type help or ? to list commands.\n'
    prompt = '(obsidian) '
    
    # Modes
    MODE_NONE = "none"
    MODE_WRITE = "write"
    MODE_REPLY = "reply"
    MODE_DECIDE = "decide"
    MODE_SEARCH = "search"
    
    def __init__(self, vault_path: str):
        super().__init__()
        self.vault_path = vault_path
        self.indexer = ObsidianIndexer(vault_path)
        self.indexer.scan_vault()
        
        self.generators = {
            self.MODE_WRITE: WritingAssistant(self.indexer),
            self.MODE_REPLY: ReplyGenerator(self.indexer),
            self.MODE_DECIDE: DecisionSupport(self.indexer),
            self.MODE_SEARCH: SearchAnalyzer(self.indexer)
        }
        
        self.current_mode = self.MODE_NONE
        self.history = [] # Stores chat history for current session
        self._set_prompt()

    def _set_prompt(self):
        if self.current_mode == self.MODE_NONE:
            self.prompt = '(obsidian) '
        else:
            turn_indicator = f" [{len(self.history)//2} turns]" if self.history else ""
            self.prompt = f'(obsidian:{self.current_mode}{turn_indicator}) '

    def do_mode(self, arg):
        """Switch mode: mode [write|reply|decide|search]"""
        if arg in [self.MODE_WRITE, self.MODE_REPLY, self.MODE_DECIDE, self.MODE_SEARCH]:
            self.current_mode = arg
            self.history = [] # Clear history on mode switch
            self._set_prompt()
            print(f"Switched to mode: {arg} (History cleared)")
        else:
            print(f"Invalid mode. Available modes: {self.MODE_WRITE}, {self.MODE_REPLY}, {self.MODE_DECIDE}, {self.MODE_SEARCH}")
            self.current_mode = self.MODE_NONE
            self.history = []
            self._set_prompt()

    def do_reload(self, arg):
        """Reloads the vault index."""
        print("Reloading index...")
        self.indexer.scan_vault()
        print("Index reloaded.")

    def do_clear(self, arg):
        """Clears the current conversation history."""
        self.history = []
        self._set_prompt()
        print("Context cleared.")

    def do_context(self, arg):
        """Show current context samples."""
        if self.current_mode == self.MODE_NONE:
            print("No mode selected.")
            return

        print(f"--- Context for {self.current_mode} ---")
        if self.current_mode == self.MODE_WRITE:
            samples = self.indexer.writing_samples
            print(f"Total Writing Samples (#writing_sample): {len(samples)}")
            for s in samples:
                print(f" - {os.path.basename(s)}")
                
        elif self.current_mode == self.MODE_REPLY:
            samples = self.indexer.reply_samples
            print(f"Total Reply Samples (#reply_sample): {len(samples)}")
            for s in samples:
                print(f" - {os.path.basename(s)}")
            print(" + REPLY-SAMPLE.md (Local)")

        elif self.current_mode == self.MODE_DECIDE:
            print("Referencing: decision.md, methodology.md")
            
        elif self.current_mode == self.MODE_SEARCH:
            print("Hybrid Search: Obsidian (Local) + DuckDuckGo (Web)")

    def default(self, line):
        """Handle input based on current mode."""
        if self.current_mode == self.MODE_NONE:
            print("Please select a mode first using `mode [write|reply|decide]`")
            return

        user_input = line.strip()
        if not user_input:
            return

        print("\nThinking...\n")
        generator = self.generators[self.current_mode]
        
        try:
            # All generators now use chat interface
            response, updated_history = generator.chat(user_input, self.history)
            
            self.history = updated_history
            self._set_prompt()
            
            print(f"\n{response}\n")
            
        except Exception as e:
            logger.error(f"Generation failed: {e}")
            print(f"Error: {e}")

    def do_quit(self, arg):
        """Quit the shell."""
        return True
    
    def do_exit(self, arg):
        """Exit the shell."""
        return True

    def emptyline(self):
        pass
