import os
import sys
import re

os.environ["ALSA_CONF_PATH"] = "/dev/null"
os.environ["PYAudio"] = "0"

from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.syntax import Syntax
from rich.console import Group
from rich.box import ROUNDED

console = Console()


class UI:
    RED = "red"
    GREEN = "green"
    YELLOW = "yellow"
    BLUE = "blue"
    MAGENTA = "magenta"
    CYAN = "cyan"
    WHITE = "white"
    RESET = "reset"
    BRIGHT = "bold"
    DIM = "dim"


def banner():
    ana_text = Text()
    ana_text.append("      █████╗ ███╗   ██╗█████╗ \n", style="cyan")
    ana_text.append("     ██╔══██╗████╗  ██║██╔══██╗\n", style="cyan")
    ana_text.append("     ███████║██╔██╗ ██║███████║\n", style="magenta")
    ana_text.append("     ██╔══██║██║╚██╗██║██╔══██║\n", style="magenta")
    ana_text.append("     ██║  ██║██║ ╚████║██║  ██║\n", style="cyan")
    ana_text.append("     ╚═╝  ╚═╝╚═╝  ╚═══╝╚═╝  ╚═╝\n", style="cyan")
    ana_text.append("\n               By DTC\n", style="bold yellow")

    content = Group(ana_text, "")

    subtitle = Text("Advanced AI Assistant", style="bold cyan")

    panel = Panel(
        content,
        title="[bold magenta]ANA[/bold magenta]",
        subtitle=subtitle,
        box=ROUNDED,
        padding=(1, 2),
        border_style="cyan",
    )

    return panel


def info(msg):
    console.print(f"[cyan][INFO][/cyan] {msg}")


def success(msg):
    console.print(f"[green][OK][/green] {msg}")


def warning(msg):
    console.print(f"[yellow][!][/yellow] {msg}")


def error(msg):
    console.print(f"[red][X][/red] {msg}")


def ana_speak(msg):
    console.print("[bold magenta]Ana:[/bold magenta]")
    _print_with_highlight(msg)


def _print_with_highlight(text):
    """Print text with syntax highlighting for code blocks"""
    pattern = r"```(\w+)?\n(.*?)```"

    parts = []
    last_end = 0

    for match in re.finditer(pattern, text, re.DOTALL):
        if match.start() > last_end:
            parts.append(("text", text[last_end : match.start()]))
        lang = match.group(1) or "python"
        code = match.group(2).rstrip()
        parts.append(("code", lang, code))
        last_end = match.end()

    if last_end < len(text):
        parts.append(("text", text[last_end:]))

    for part in parts:
        if part[0] == "text":
            console.print(part[1])
        elif part[0] == "code":
            _, lang, code = part
            syntax = Syntax(code, lang, theme="monokai", line_numbers=True)
            console.print(syntax)
            console.print()


def user_input():
    return console.input("[cyan]You:[/cyan] ")


def ana_box(text, title="Ana"):
    return Panel(text, title=title, box=ROUNDED, border_style="cyan", padding=1)


def print_code(code, language="python"):
    """Print code with syntax highlighting"""
    syntax = Syntax(code, language, theme="monokai", line_numbers=True)
    console.print(syntax)
