import argparse
import sys
import os

from .config import load_config, save_config
from .engine import generate_voice
from .audio import play
from .matcher import suggest

def handle_command(cmd):
    config = load_config()

    voice_sample = config.get("voice_sample")
    rules = config.get("rules", {})

    if cmd in rules:
        text = rules[cmd]
    else:
        suggestion = suggest(cmd)
        if suggestion:
            text = f"Command not found. Did you mean {suggestion}"
        else:
            text = "Command not found"

    print(f"Speaking: {text}")
    audio_file = generate_voice(text, voice_sample)
    
    if audio_file:
        play(audio_file)

def upload_voice(path):
    config = load_config()
    abs_path = os.path.abspath(path)
    if not os.path.exists(abs_path):
        print(f"Error: File not found at {abs_path}")
        sys.exit(1)
        
    config["voice_sample"] = abs_path
    save_config(config)

    print("Voice uploaded successfully")

def add_rule(cmd, text):
    config = load_config()

    if "rules" not in config:
        config["rules"] = {}

    config["rules"][cmd] = text

    save_config(config)

    print("Rule added")

def main():
    parser = argparse.ArgumentParser(description="Terminal Voice - Intercept failed commands with voice")
    subparsers = parser.add_subparsers(dest="command")
    subparsers.required = True

    speak_parser = subparsers.add_parser("speak", help="Speak a message for a failed command")
    speak_parser.add_argument("cmd", help="The command that failed")

    upload_parser = subparsers.add_parser("upload-voice", help="Upload a voice sample (.wav) to clone")
    upload_parser.add_argument("file", help="Path to the .wav voice file")

    rule_parser = subparsers.add_parser("add-rule", help="Add a custom rule/message for a command")
    rule_parser.add_argument("cmd", help="The command")
    rule_parser.add_argument("text", help="The text to speak")

    args = parser.parse_args()

    if args.command == "speak":
        handle_command(args.cmd)
    elif args.command == "upload-voice":
        upload_voice(args.file)
    elif args.command == "add-rule":
        add_rule(args.cmd, args.text)

if __name__ == "__main__":
    main()
