from __future__ import annotations
import time
from ..voice import PhraseMatcher

class AssistantManager:
    def __init__(self, name="Nest", wake_word="nest", mode="hybrid", cooldown_seconds=0.5):
        self.name = name
        self.wake_word = wake_word.lower().strip()
        self.mode = mode
        self.cooldown_seconds = cooldown_seconds
        self.last_run = 0.0
        self.transcript = []
        self.matcher = PhraseMatcher()
        self.commands = {}
        self.voice_enabled = True
        self.listening_enabled = True
        self.confirm_dangerous = True

    def register_command(self, name, phrases, callback=None, dangerous=False):
        self.commands[name] = {"callback": callback, "dangerous": dangerous}
        self.matcher.register(name, *phrases)

    def can_run(self):
        now = time.time()
        if now - self.last_run < self.cooldown_seconds:
            return False
        self.last_run = now
        return True

    def hear(self, text: str):
        self.transcript.append({"heard": text})
        if not self.can_run():
            return {"status": "cooldown", "heard": text}
        normalized = text.strip()
        lowered = normalized.lower()
        if self.wake_word and lowered.startswith(self.wake_word + " "):
            normalized = normalized[len(self.wake_word):].strip()
        match = self.matcher.match(normalized)
        if not match:
            return {"status": "unmatched", "heard": text}
        command = self.commands.get(match["name"], {})
        if command.get("dangerous") and self.confirm_dangerous:
            return {"status": "confirm_required", "command": match["name"], "heard": text}
        callback = command.get("callback")
        result = callback(normalized) if callback else None
        return {"status": "executed", "command": match["name"], "heard": text, "result": result}
