"""OLED detour: The Endless Landscape (after Phase 5, before Phase 6).

Lesson: https://mdm508.github.io/post/the-endless-landscape/
Run this file ON THE PICO using Thonny or MicroPico in VS Code.
Keep ssd1306.py in the SAME FOLDER ON THE PICO, from the Phase 1 kit.
Wiring: GP0 -> SDA, GP1 -> SCL, 3V3(OUT) -> VCC, GND -> GND.

Only setup runs. Write your implementations below it; the prompts and
supplied scaffolds are comments. Keep useful functions, replace experiment
calls, and run the WHOLE file. No input() or preserved session is needed.
Use finite animations while developing; only try an endless loop after tests.

The PNG converter runs in landscape-image-lab.py ON YOUR COMPUTER.
Pillow does not run in this Pico lab. Later, upload landscape.bin to the Pico.
"""

import framebuf
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
from time import sleep_ms, ticks_us, ticks_diff

VIEW_WIDTH = 128
VIEW_HEIGHT = 64
WORLD_WIDTH = 384

i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=200_000)
oled = SSD1306_I2C(VIEW_WIDTH, VIEW_HEIGHT, i2c)
world_data = bytearray(WORLD_WIDTH * (VIEW_HEIGHT // 8))
world = framebuf.FrameBuffer(
    world_data, WORLD_WIDTH, VIEW_HEIGHT, framebuf.MONO_VLSB
)

# Q1: derive which world column supplies each screen column.
# Work with the tiny browser model before writing the renderer.

# Q2: calculate both pictures' storage; correct Henry's explanation.
# Draw a temporary world with recognizable landmarks, using a loop.
# def build_world(world, width, height):
#     """Clear/draw the world. Do not show()."""
#     pass

# Q3: implement the pixel renderer and offset update using your Q1 rule.
# def draw_window(world, target, image_width, offset,
#                 view_width=128, height=64):
#     """Copy every window pixel, including zeros; do not show()."""
#     pass
#
# def advance_offset(offset, image_width, speed):
#     """Return a valid wrapped offset. Integer speed may be negative."""
#     pass
#
# assert advance_offset(383, 384, 1) == 0
# assert advance_offset(382, 384, 5) == 3
# assert advance_offset(2, 384, -5) == 381
# Test single windows at 0, 100, 256, 257, 300, and 383 before animating.
# Translate the lesson's render/show/advance/pause plan into a finite loop.
# Build the world once, outside that loop. Keep the original world unchanged.

# Q4: supplied timing scaffold; uncomment AFTER your renderer works.
# Build the world first, then repeat the samples and report their range.
# render_times = []
# transfer_times = []
# for offset in (0, 100, 256, 300, 383):
#     start = ticks_us()
#     draw_window(world, oled, WORLD_WIDTH, offset)
#     rendered = ticks_us()
#     oled.show()
#     sent = ticks_us()
#     render_times.append(ticks_diff(rendered, start))
#     transfer_times.append(ticks_diff(sent, rendered))
# print("Render samples (us):", render_times)
# print("Transfer samples (us):", transfer_times)

# Q5: implement page-wise byte copying. Arrays have separate storage,
# matching MONO_VLSB layouts, default stride, and equal height divisible by 8.
# Preserve destination length and copy dark states too. Do not show().
# def draw_window_fast(source, destination, source_width, offset,
#                      view_width=128, height=64):
#     pass
# Compare with the slow renderer using a bytes() snapshot at each offset:
# 0, 100, 256, 257, 300, 383, 384, -1. Check length and unchanged world too.
# Then time this renderer with Q4's same offsets; keep show() timing separate.

# Q6 runs in the DESKTOP file. Verify tiny known bytes and decode the artwork
# before uploading landscape.bin onto the Pico beside this program.

# Q7: supplied file loader (not an implementation puzzle).
# Uncomment this definition and put it BEFORE the replacement allocation.
# def load_image(filename, width, height):
#     if width < 128 or height != 64:
#         raise ValueError("Use a world at least 128 wide and exactly 64 high")
#     expected_size = width * (height // 8)
#     with open(filename, "rb") as file:
#         pixels = bytearray(file.read())
#     if len(pixels) != expected_size:
#         raise ValueError("Unexpected image size; check the dimensions and file")
#     image = framebuf.FrameBuffer(pixels, width, height, framebuf.MONO_VLSB)
#     return pixels, image
#
# Set WORLD_WIDTH above to the exact artwork width. REPLACE the original
# world_data/world allocation with this call, placed AFTER load_image's def:
# world_data, world = load_image("landscape.bin", WORLD_WIDTH, VIEW_HEIGHT)
# Remove build_world() calls that would overwrite your loaded artwork.
# Keep your rendering functions, then write a finite trip with the fast one.
# Check the final-world-column -> zero seam before trying while True.
