#!/usr/bin/env python3
"""ASCII image fallback for brt -image."""

import sys


ASCII_CHARS = "@%#*+=-:. "


def load_ppm(path: str) -> tuple[int, int, bytes]:
    with open(path, "rb") as f:
        magic = f.readline().strip()
        if magic not in (b"P6", b"P5"):
            raise ValueError(f"Unsupported PPM magic: {magic!r}")

        def _read_line() -> bytes:
            line = f.readline()
            while line.startswith(b"#"):
                line = f.readline()
            return line

        dims = _read_line().decode().strip().split()
        width, height = int(dims[0]), int(dims[1])
        maxval = int(_read_line().decode().strip())
        if maxval > 255:
            raise ValueError("Only 8-bit PPM is supported")

        if magic == b"P6":
            data = f.read(width * height * 3)
        else:
            gray = f.read(width * height)
            data = bytes(ch for px in gray for ch in (px, px, px))
    return width, height, data


def render_ascii(path: str, width: int, height: int = 0) -> None:
    img_w, img_h, rgb = load_ppm(path)
    if width <= 0:
        width = min(100, img_w)

    aspect = img_h / img_w
    if height <= 0:
        height = max(1, int(width * aspect * 0.55))
    out = []

    for y in range(height):
        row = []
        for x in range(width):
            src_x = min(img_w - 1, int(x * img_w / width))
            src_y = min(img_h - 1, int(y * img_h / height))
            idx = (src_y * img_w + src_x) * 3
            r, g, b = rgb[idx], rgb[idx + 1], rgb[idx + 2]
            lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
            char_idx = int(lum / 255 * (len(ASCII_CHARS) - 1))
            row.append(ASCII_CHARS[char_idx])
        out.append("".join(row))
    print("\n".join(out))


def main() -> int:
    if len(sys.argv) < 2:
        print("usage: media.py ascii <ppm-file> <width> [height]", file=sys.stderr)
        return 1

    mode = sys.argv[1]
    if mode != "ascii":
        print("usage: media.py ascii <ppm-file> <width> [height]", file=sys.stderr)
        return 1

    if len(sys.argv) < 4:
        print("usage: media.py ascii <ppm-file> <width> [height]", file=sys.stderr)
        return 1

    path = sys.argv[2]
    width = int(sys.argv[3])
    height = int(sys.argv[4]) if len(sys.argv) > 4 else 0
    render_ascii(path, width, height)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
