"""Utility helpers: local IP, QR code, log tailing."""

from __future__ import annotations

import socket
from pathlib import Path
from typing import Iterator


def get_local_ip() -> str:
    """Return the machine's LAN IP address."""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.connect(("8.8.8.8", 80))
        ip = sock.getsockname()[0]
        sock.close()
        return ip
    except Exception:
        return "127.0.0.1"


def generate_qr(url: str) -> str:
    """Return an ASCII QR code string for the given URL."""
    try:
        import qrcode
        import io

        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=1,
            border=2,
        )
        qr.add_data(url)
        qr.make(fit=True)

        buf = io.StringIO()
        qr.print_ascii(out=buf, invert=True)
        return buf.getvalue()
    except Exception as exc:
        return f"(QR generation failed: {exc})\nURL: {url}"


def tail_log(path: Path, n: int = 50) -> Iterator[str]:
    """Yield the last N lines of a file."""
    try:
        with open(path, "r") as f:
            lines = f.readlines()
            yield from lines[-n:]
    except Exception:
        return
