#!/usr/bin/env python3
# starfield - short animated starfield (frame-limited, so it always exits)
# Usage: starfield [--frames N] [--width W] [--height H] [--seed N]
import argparse, random, sys, time

def frame(stars, w, h):
    grid = [[" "] * w for _ in range(h)]
    for x, y, _speed, ch in stars:
        if 0 <= int(y) < h and 0 <= int(x) < w:
            grid[int(y)][int(x)] = ch
    return "\n".join("".join(row) for row in grid)

def run(frames, w, h, seed=None, delay=0.08, out=None):
    rng = random.Random(seed)
    stars = []
    for _ in range(max(10, w * h // 40)):
        speed = rng.choice([1, 1, 2, 3])
        ch = "." if speed == 1 else ("+" if speed == 2 else "*")
        stars.append([rng.uniform(0, w - 1), rng.uniform(0, h - 1), speed, ch])
    cx, cy = w / 2, h / 2
    for f in range(frames):
        for s in stars:
            # stars drift outward from the centre, faster ones move more
            dx, dy = s[0] - cx, s[1] - cy
            dist = max(1.0, (dx * dx + dy * dy) ** 0.5)
            s[0] += dx / dist * s[2] * 0.6
            s[1] += dy / dist * s[2] * 0.6
            if not (0 <= s[0] < w and 0 <= s[1] < h):
                # respawn near the centre
                s[0] = cx + rng.uniform(-2, 2)
                s[1] = cy + rng.uniform(-1, 1)
        text = frame(stars, w, h)
        if out is not None:
            out.append(text)
        else:
            print("\033[2J\033[H", end="")
            print(f"Starfield — frame {f+1}/{frames}")
            print(text)
            if delay:
                time.sleep(delay)
    return stars

def selftest():
    frames = []
    stars = run(3, 40, 10, seed=1, delay=0, out=frames)
    assert len(frames) == 3, len(frames)
    assert all("*" in f or "+" in f or "." in f for f in frames)
    assert len(stars) > 0
    print(frames[0])
    print("starfield selftest OK")

def main():
    p = argparse.ArgumentParser(description="Short animated starfield (frame-limited, so it always exits).")
    p.add_argument("--frames", type=int, default=30, help="number of frames (default 30)")
    p.add_argument("--width", type=int, default=60, help="field width (default 60)")
    p.add_argument("--height", type=int, default=20, help="field height (default 20)")
    p.add_argument("--seed", type=int, default=None, help="seed for deterministic stars")
    p.add_argument("--delay", type=float, default=0.08, help="seconds per frame")
    p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    a = p.parse_args()
    if a.selftest:
        selftest(); return 0
    if a.frames < 1:
        p.error("frames must be >= 1")
    run(a.frames, a.width, a.height, a.seed, a.delay)
    return 0

if __name__ == "__main__":
    sys.exit(main())
