from .color import predefined_colors

def gradient(start_color, end_color, text):
    def parse_color(c):
        if isinstance(c, str):
            c = c.lower()
            if c in predefined_colors:
                c = predefined_colors[c]
            if c.startswith("#"):
                c = c.lstrip("#")
                return tuple(int(c[i:i+2], 16) for i in (0, 2, 4))
        elif isinstance(c, tuple) and len(c) == 3:
            return c
        raise ValueError("Color must be a hex string, RGB tuple, or predefined name.")

    r1, g1, b1 = parse_color(start_color)
    r2, g2, b2 = parse_color(end_color)

    n = len(text)
    output = ""
    for i, char in enumerate(text):
        r = int(r1 + (r2 - r1) * i / max(n - 1, 1))
        g = int(g1 + (g2 - g1) * i / max(n - 1, 1))
        b = int(b1 + (b2 - b1) * i / max(n - 1, 1))
        output += f"\033[38;2;{r};{g};{b}m{char}"
    output += "\033[0m"
    return output