#!/usr/bin/env python3
import curses
import urllib.request
from html import unescape
from html.parser import HTMLParser

BASE_URL = "https://scratch.mit.edu/site-api/comments/user/griffpatch/?page={page}"

class ScratchCommentParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.comments = []
        self.in_content = False
        self.current_author = None
        self.current_text = []

    def handle_starttag(self, tag, attrs):
        attr_dict = dict(attrs)
        # Extract author from element attribute
        if 'data-comment-user' in attr_dict:
            self.current_author = attr_dict['data-comment-user']

        # Content lives inside <div class="content">
        if tag == 'div' and attr_dict.get('class') == 'content':
            self.in_content = True
            self.current_text = []

    def handle_endtag(self, tag):
        if tag == 'div' and self.in_content:
            self.in_content = False
            text = unescape(' '.join(''.join(self.current_text).split()))
            if self.current_author and text:
                self.comments.append((self.current_author, text))

    def handle_data(self, data):
        if self.in_content:
            self.current_text.append(data)

def fetch_profile_comments(page=1):
    url = BASE_URL.format(page=page)
    req = urllib.request.Request(
        url,
        headers={
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0',
            'X-Requested-With': 'XMLHttpRequest'
        }
    )
    try:
        with urllib.request.urlopen(req, timeout=5) as response:
            html = response.read().decode('utf-8', errors='ignore')
            parser = ScratchCommentParser()
            parser.feed(html)
            return parser.comments if parser.comments else [("SYSTEM", f"No comments found on page {page}.")]
    except Exception as e:
        return [("SYSTEM", f"Network error on page {page}: {e}")]

def main(stdscr):
    curses.curs_set(0)
    curses.use_default_colors()

    if curses.has_colors():
        curses.init_pair(1, curses.COLOR_CYAN, -1)   # Usernames
        curses.init_pair(2, curses.COLOR_YELLOW, -1) # Headers
        curses.init_pair(3, curses.COLOR_GREEN, -1)  # Footers

    current_page = 1
    scroll_offset = 0

    # Initial fetch
    stdscr.clear()
    stdscr.addstr(0, 0, f"Fetching Griffpatch comments (Page {current_page})...", curses.A_BOLD)
    stdscr.refresh()
    comments = fetch_profile_comments(page=current_page)

    while True:
        stdscr.clear()
        height, width = stdscr.getmaxyx()

        # Header with active page indicator
        header = f" === GRIFFPATCH PROFILE COMMENTS | PAGE {current_page} | [R]efresh | [Q]uit === "
        stdscr.addstr(0, 0, header[:width-1], curses.color_pair(2) | curses.A_BOLD)

        # Build view buffer from parsed comments
        display_lines = []
        for author, content in comments:
            display_lines.append((f"@{author}:", curses.color_pair(1) | curses.A_BOLD))

            # Simple text wrapping
            words = content.split(' ')
            line = "  "
            for word in words:
                if len(line) + len(word) + 1 < width - 2:
                    line += word + " "
                else:
                    display_lines.append((line, curses.A_NORMAL))
                    line = "  " + word + " "
            if line.strip():
                display_lines.append((line, curses.A_NORMAL))

            display_lines.append(("", curses.A_NORMAL)) # Spacer line between comments

        max_visible_lines = height - 2
        visible_lines = display_lines[scroll_offset:scroll_offset + max_visible_lines]

        # Draw lines
        for idx, (text, attr) in enumerate(visible_lines):
            try:
                stdscr.addstr(idx + 1, 0, text[:width-1], attr)
            except curses.error:
                pass

        # Footer with arrow navigation instructions
        total_lines = len(display_lines) if display_lines else 1
        status = f" Line: {scroll_offset+1}/{total_lines} | Page: {current_page} | UP/DOWN: Scroll | LEFT/RIGHT: Page "
        try:
            stdscr.addstr(height - 1, 0, status[:width-1], curses.color_pair(3))
        except curses.error:
            pass

        stdscr.refresh()

        # Input handling
        key = stdscr.getch()

        if key in (ord('q'), ord('Q')):
            break
        elif key in (ord('r'), ord('R')):
            stdscr.clear()
            stdscr.addstr(0, 0, f"Refreshing page {current_page}...", curses.color_pair(2))
            stdscr.refresh()
            comments = fetch_profile_comments(page=current_page)
            scroll_offset = 0
        elif key == curses.KEY_DOWN:
            if scroll_offset < max(0, len(display_lines) - max_visible_lines):
                scroll_offset += 1
        elif key == curses.KEY_UP:
            if scroll_offset > 0:
                scroll_offset -= 1
        elif key == curses.KEY_RIGHT:
            # Next page (older comments)
            current_page += 1
            scroll_offset = 0
            stdscr.clear()
            stdscr.addstr(0, 0, f"Loading Page {current_page}...", curses.color_pair(2))
            stdscr.refresh()
            comments = fetch_profile_comments(page=current_page)
        elif key == curses.KEY_LEFT:
            # Previous page (newer comments)
            if current_page > 1:
                current_page -= 1
                scroll_offset = 0
                stdscr.clear()
                stdscr.addstr(0, 0, f"Loading Page {current_page}...", curses.color_pair(2))
                stdscr.refresh()
                comments = fetch_profile_comments(page=current_page)

if __name__ == "__main__":
    curses.wrapper(main)
