# MIT License
#
# Copyright (c) 2026 BitBlur
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""BitBlur Library. Render a four-second loop with Python; FFmpeg encodes MP4."""
import argparse
import math
import subprocess
from pathlib import Path

FPS = 24
FRAMES = FPS * 4
INK = (8, 16, 26)


def render(frame, width, height):
    pixels = bytearray(bytes(INK) * (width * height))
    phase = math.tau * (frame % FRAMES) / FRAMES

    def block(x, y, radius, color):
        left, right = max(0, x-radius), min(width, x+radius+1)
        if right <= left:
            return
        row = bytes(color) * (right-left)
        for line in range(max(0, y-radius), min(height, y+radius+1)):
            start = 3 * (line * width + left)
            pixels[start:start+len(row)] = row

    scale = min(width, height)
    for step in range(120):
        angle = math.tau * step / 120
        pulse = (0.5 + 0.5 * math.cos(angle-phase)) ** 10
        x = int(width/2 + scale*.41*math.sin(angle))
        y = int(height/2 + scale*.23*math.sin(2*angle))
        shade = int(76 + 167*pulse)
        block(x, y, 1+int(2*pulse), (int(shade*.75), shade, min(255, shade+22)))
    return bytes(pixels)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("output", type=Path, help="New .ppm still or .mp4 movie")
    parser.add_argument("--portrait", action="store_true")
    parser.add_argument("--frame", type=int, default=0, help="Still frame number")
    args = parser.parse_args()
    w, h = (180, 320) if args.portrait else (320, 180)
    if args.output.suffix.lower() == ".ppm":
        with args.output.open("xb") as out:
            out.write(f"P6\n{w} {h}\n255\n".encode() + render(args.frame, w, h))
        return
    if args.output.suffix.lower() != ".mp4":
        parser.error("Choose a .ppm or .mp4 output")
    command = ["ffmpeg", "-loglevel", "error", "-n", "-f", "rawvideo", "-pix_fmt",
               "rgb24", "-s", f"{w}x{h}", "-framerate", str(FPS), "-i", "-",
               "-vf", "scale=iw*4:ih*4:flags=neighbor", "-c:v", "libx264",
               "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(args.output)]
    with subprocess.Popen(command, stdin=subprocess.PIPE) as encoder:
        try:
            for frame in range(FRAMES):
                encoder.stdin.write(render(frame, w, h))
        finally:
            encoder.stdin.close()
        if encoder.wait():
            raise SystemExit("FFmpeg could not finish the movie.")


if __name__ == "__main__":
    main()
