"""
ANSI escape codes, terminal size helpers, and text output primitives.
No internal dependencies.
"""

import os
import random
import sys
import time

# ─── ANSI ─────────────────────────────────────────────────
RST = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
# Matrix greens
G_HI = "\033[38;5;46m"
G_MID = "\033[38;5;34m"
G_LO = "\033[38;5;22m"
G_DIM = "\033[2;38;5;34m"
# THX-1138 sterile tones
W_COOL = "\033[38;5;250m"
W_DIM = "\033[2;38;5;245m"
W_GHOST = "\033[2;38;5;238m"
C_DIM = "\033[2;38;5;37m"
# Terminal control
CLR = "\033[2J\033[H"
CURSOR_OFF = "\033[?25l"
CURSOR_ON = "\033[?25h"


# ─── TERMINAL SIZE ────────────────────────────────────────
def tw():
    try:
        return os.get_terminal_size().columns
    except Exception:
        return 80


def th():
    try:
        return os.get_terminal_size().lines
    except Exception:
        return 24


# ─── TEXT OUTPUT ──────────────────────────────────────────
def type_out(text, color=G_HI):
    i = 0
    while i < len(text):
        if random.random() < 0.3:
            b = random.randint(2, 5)
            sys.stdout.write(f"{color}{text[i : i + b]}{RST}")
            i += b
        else:
            sys.stdout.write(f"{color}{text[i]}{RST}")
            i += 1
        sys.stdout.flush()
        time.sleep(random.uniform(0.004, 0.018))


def slow_print(text, color=G_DIM, delay=0.015):
    for ch in text:
        sys.stdout.write(f"{color}{ch}{RST}")
        sys.stdout.flush()
        time.sleep(delay)


def boot_ln(label, status, ok=True):
    dots = max(3, min(30, tw() - len(label) - len(status) - 8))
    sys.stdout.write(f"  {G_DIM}>{RST} {W_DIM}{label} ")
    sys.stdout.flush()
    for _ in range(dots):
        sys.stdout.write(f"{G_LO}.")
        sys.stdout.flush()
        time.sleep(random.uniform(0.006, 0.025))
    c = G_MID if ok else "\033[2;38;5;196m"
    print(f" {c}{status}{RST}")
    time.sleep(random.uniform(0.02, 0.1))
