#!/usr/bin/env python
import sys
try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib
import yfinance as yf

if sys.stdout.isatty():
    print("\033]0;stock-view\007", end="", flush=True)

GREEN = "\033[32m"
RED = "\033[31m"
DIM = "\033[2m"
BOLD = "\033[1m"
RESET = "\033[0m"

CHART_HEIGHT = 8

BRAILLE_DOTS = [
    [0x01, 0x08],
    [0x02, 0x10],
    [0x04, 0x20],
    [0x40, 0x80],
]


def braille_char(top, bottom):
    bits = 0
    if top:
        bits |= 0x04
    if bottom:
        bits |= 0x20
    return chr(0x2800 | bits)


def render_chart(prices, width=60, height=CHART_HEIGHT):
    if len(prices) < 2:
        return ["no data"] * height

    lo, hi = min(prices), max(prices)
    span = hi - lo or 1

    def row_for(price):
        return int((price - lo) / span * (height - 1))

    cols = []
    step = len(prices) / width
    for i in range(width):
        idx = int(i * step)
        cols.append(prices[min(idx, len(prices) - 1)])

    rows = [[" "] * width for _ in range(height)]
    for x, price in enumerate(cols):
        r = row_for(price)
        rows[height - 1 - r][x] = "│" if x == 0 else "█"

    # fill below the line
    for x, price in enumerate(cols):
        r = row_for(price)
        for y in range(height - 1 - r + 1, height):
            if rows[y][x] == " ":
                rows[y][x] = "░"

    return ["".join(row) for row in rows]


def fetch(ticker):
    t = yf.Ticker(ticker)
    hist = t.history(period="5d", interval="30m")
    if hist.empty:
        return None, None, None
    closes = hist["Close"].tolist()
    info = t.fast_info
    current = closes[-1]
    prev_close = info.previous_close if hasattr(info, "previous_close") else closes[0]
    return closes, current, prev_close


def fmt_price(p):
    return f"${p:>9.2f}"


def fmt_change(current, prev):
    delta = current - prev
    pct = delta / prev * 100
    sign = "+" if delta >= 0 else ""
    color = GREEN if delta >= 0 else RED
    return f"{color}{sign}{delta:.2f} ({sign}{pct:.2f}%){RESET}"


def main():
    with open("config.toml", "rb") as f:
        config = tomllib.load(f)

    tickers = config["stocks"]["tickers"]
    import shutil
    term_width = shutil.get_terminal_size((80, 24)).columns
    chart_w = term_width - 6

    print()
    for ticker in tickers:
        print(f"  {DIM}fetching {ticker}...{RESET}", end="\r", flush=True)
        closes, current, prev_close = fetch(ticker)
        print(" " * 30, end="\r")

        if closes is None:
            print(f"  {BOLD}{ticker:<6}{RESET}  {RED}no data{RESET}\n")
            continue

        color = GREEN if current >= prev_close else RED
        change_str = fmt_change(current, prev_close)
        chart_lines = render_chart(closes, width=chart_w, height=CHART_HEIGHT)

        header = f"  {BOLD}{color}{ticker:<6}{RESET}  {fmt_price(current)}  {change_str}"
        print(header)

        bar_color = GREEN if current >= prev_close else RED
        for i, line in enumerate(chart_lines):
            if i == CHART_HEIGHT - 1:
                label = f"  {DIM}5d{RESET} "
            else:
                label = "     "
            print(f"{label}{bar_color}{line}{RESET}")
        print()


if __name__ == "__main__":
    main()
