#!/usr/bin/env python

import os
import sys
from functools import lru_cache

if __name__ == '__main__' and not __package__:
    import __main__
    __main__.__package__ = 'gen'
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def to_linear(a: float) -> float:
    if a <= 0.04045:
        return a / 12.92
    else:
        return float(pow((a + 0.055) / 1.055, 2.4))


@lru_cache
def generate_srgb_lut(line_prefix: str = '    ') -> list[str]:
    values: list[str] = []
    lines: list[str] = []

    for i in range(256):
        values.append(f'{to_linear(i / 255.0):1.5f}f')

    for i in range(16):
        lines.append(line_prefix + ', '.join(values[i * 16:(i + 1) * 16]) + ',')

    lines[-1] = lines[-1].rstrip(',')
    return lines


def generate_srgb_gamma(declaration: str = 'static const GLfloat srgb_lut[256] = {', close: str = '};') -> str:
    lines: list[str] = []
    a = lines.append

    a('// Generated by gen-srgb-lut.py DO NOT edit')
    a('')
    a(declaration)
    lines += generate_srgb_lut()
    a(close)

    return "\n".join(lines)


def main(args: list[str]=sys.argv) -> None:
    c = generate_srgb_gamma()
    with open(os.path.join('kitty', 'srgb_gamma.h'), 'w') as f:
        f.write(f'{c}\n')


if __name__ == '__main__':
    import runpy
    m = runpy.run_path(os.path.dirname(os.path.abspath(__file__)))
    m['main']([sys.executable, 'srgb-lut'])
