"""Log viewer view."""
from django.shortcuts import render
from django.http import HttpResponse


def log_viewer(request):
    """Display last 200 lines of the app log (DEBUG only).
    With ?pos=N, returns text: line_count\\nnew_content for AJAX polling.
    """
    from django.conf import settings
    if not settings.DEBUG:
        return HttpResponse('Log viewer only available in DEBUG mode', status=403)
    log_path = settings.BASE_DIR / 'logs' / 'tianxuan.log'
    pos = request.GET.get('pos')
    if pos is not None:
        # AJAX polling mode: return new content since byte position
        try:
            pos = int(pos)
        except ValueError:
            pos = 0
        if log_path.exists():
            with open(log_path, 'r', encoding='utf-8') as f:
                total = f.seek(0, 2)  # seek to end
                if pos >= total:
                    return HttpResponse(f'{total}\n', content_type='text/plain')
                f.seek(pos)
                new_content = f.read()
                return HttpResponse(f'{total}\n{new_content}', content_type='text/plain')
        return HttpResponse('0\n', content_type='text/plain')

    # HTML page mode
    lines = []
    if log_path.exists():
        with open(log_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()[-200:]
    return render(request, 'tianxuan/log_viewer.html', {'lines': lines})
