#!/usr/bin/env python3
# 파일명  : yyy_tail.py
# 파일위치: /data/_py/yyy_tail.py
# 내용

import os
import sys
import json
import html
import time
from collections import deque

def jprint(obj):
    sys.stdout.write(json.dumps(obj, ensure_ascii=False))

def read_tail(path, n):
    q = deque(maxlen=n)
    with open(path, 'r', encoding='utf-8', errors='replace') as f:
        for line in f:
            q.append(line.rstrip('\n'))
    return list(q)

def html_wrap(title, body):
    return f"""<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{html.escape(title)}</title>
</head>
<body style="margin:0;padding:16px;background:#111;color:#eee;font-family:Consolas,Monaco,monospace;">
  <div style="font-size:18px;font-weight:700;margin-bottom:12px;">{html.escape(title)}</div>
  <pre style="margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.55;background:#1b1b1b;border:1px solid #333;border-radius:8px;padding:14px;">{body}</pre>
</body>
</html>"""

def main():
    try:
        req = json.load(sys.stdin)

        path  = (req.get('path') or '').strip()
        n     = int(req.get('n', 80) or 80)
        fmt   = (req.get('fmt') or 'html').strip().lower()
        grep  = req.get('grep') or ''
        icase = bool(req.get('icase', True))

        if not path:
            return jprint({'ok': False, 'error': 'path 누락'})
        if not os.path.isfile(path):
            return jprint({'ok': False, 'error': '파일 없음', 'path': path})

        n = max(1, min(2000, n))

        lines = read_tail(path, n)

        if grep:
            if icase:
                g = grep.lower()
                lines = [ln for ln in lines if g in ln.lower()]
            else:
                lines = [ln for ln in lines if grep in ln]

        text = '\n'.join(lines)
        title = f"tail {n} lines"
        if grep:
            title += f" | grep={grep}"
        title += f" | {path}"

        if fmt == 'text':
            out = title + "\n" + ("-" * min(len(title), 120)) + "\n" + text + "\n"
        else:
            out = html_wrap(title, html.escape(text))

        return jprint({
            'ok': True,
            'path': path,
            'n': n,
            'grep': grep,
            'count': len(lines),
            'output': out
        })

    except Exception as e:
        return jprint({
            'ok': False,
            'error': str(e)
        })

if __name__ == '__main__':
    main()