#!/usr/bin/env python3
import curses
import urllib.request
import urllib.error
import json
import sys
from datetime import datetime
from html.parser import HTMLParser

HEADERS = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"}

def fetch_data(url):
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        with urllib.request.urlopen(req, timeout=5) as response:
            return response.read().decode('utf-8')
    except Exception:
        return None

def format_timestamp(raw_time):
    if not raw_time or raw_time == "N/A":
        return "N/A"
    try:
        clean_time = raw_time.replace('Z', '')
        dt = datetime.fromisoformat(clean_time)
        return dt.strftime("%Y-%m-%d %H:%M")
    except Exception:
        # Fallback for relative strings like "2 hours ago" or pre-formatted HTML dates
        return raw_time.strip()


# Overhauled parser for profile wall comments (HTML)
class ProfileCommentParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.comments = []
        self.current_comment = None
        self.in_author = False
        self.in_content = False
        self.in_time = False

    def handle_starttag(self, tag, attrs):
        attrs_dict = dict(attrs)
        tag_class = attrs_dict.get('class', '').split()

        if 'comment' in tag_class:
            c_id = attrs_dict.get('data-comment-id', '0')
            self.current_comment = {"id": c_id, "author": "", "content": "", "time": "N/A"}

        if self.current_comment:
            if tag in ('a', 'div') and any(c in tag_class for c in ('name', 'user', 'actor')):
                self.in_author = True
            elif tag == 'div' and 'content' in tag_class:
                self.in_content = True
            elif tag in ('span', 'div', 'a') and any(c in tag_class for c in ('time', 'date', 'datetime')):
                self.in_time = True
                if 'title' in attrs_dict:
                    self.current_comment["time"] = format_timestamp(attrs_dict['title'])

    def handle_endtag(self, tag):
        if self.in_author and tag in ('a', 'div'):
            self.in_author = False
        if self.in_content and tag == 'div':
            self.in_content = False
            if self.current_comment:
                author = self.current_comment["author"].strip() or "Unknown"
                content = " ".join(self.current_comment["content"].split())
                c_time = self.current_comment["time"].strip() or "N/A"
                self.comments.append((
                    author,
                    content,
                    self.current_comment["id"],
                    c_time,
                    False # is_reply
                ))
                self.current_comment = None
        if self.in_time and tag in ('span', 'div', 'a'):
            self.in_time = False

    def handle_data(self, data):
        if self.in_author and self.current_comment:
            text = data.strip()
            if text and not self.current_comment["author"]:
                self.current_comment["author"] = text
        elif self.in_content and self.current_comment:
            self.current_comment["content"] += data
        elif self.in_time and self.current_comment and self.current_comment["time"] in ("N/A", ""):
            text = data.strip()
            if text:
                self.current_comment["time"] = format_timestamp(text)


# Parser for studio comments (HTML via site-api)
class StudioCommentParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.comments = []
        self.current_comment = None
        self.in_author = False
        self.in_content = False
        self.in_time = False

    def handle_starttag(self, tag, attrs):
        attrs_dict = dict(attrs)
        tag_class = attrs_dict.get('class', '').split()

        if 'comment' in tag_class:
            c_id = attrs_dict.get('data-comment-id', '0')
            self.current_comment = {"id": c_id, "author": "", "content": "", "time": "N/A"}

        if self.current_comment:
            if tag in ('a', 'div') and any(c in tag_class for c in ('name', 'user', 'actor')):
                self.in_author = True
            elif tag == 'div' and 'content' in tag_class:
                self.in_content = True
            elif tag in ('span', 'div', 'a') and any(c in tag_class for c in ('time', 'date', 'datetime')):
                self.in_time = True
                if 'title' in attrs_dict:
                    self.current_comment["time"] = format_timestamp(attrs_dict['title'])

    def handle_endtag(self, tag):
        if self.in_author and tag in ('a', 'div'):
            self.in_author = False
        if self.in_content and tag == 'div':
            self.in_content = False
            if self.current_comment:
                author = self.current_comment["author"].strip() or "Unknown"
                content = " ".join(self.current_comment["content"].split())
                c_time = self.current_comment["time"].strip() or "N/A"
                self.comments.append((
                    author,
                    content,
                    self.current_comment["id"],
                    c_time,
                    False
                ))
                self.current_comment = None
        if self.in_time and tag in ('span', 'div', 'a'):
            self.in_time = False

    def handle_data(self, data):
        if self.in_author and self.current_comment:
            text = data.strip()
            if text and not self.current_comment["author"]:
                self.current_comment["author"] = text
        elif self.in_content and self.current_comment:
            self.current_comment["content"] += data
        elif self.in_time and self.current_comment and self.current_comment["time"] in ("N/A", ""):
            text = data.strip()
            if text:
                self.current_comment["time"] = format_timestamp(text)


def fetch_comments(username, mode="profile", page=1, project_id=None, studio_id=None):
    if mode == "profile":
        url = f"https://scratch.mit.edu/site-api/comments/user/{username}/?page={page}"
        html_data = fetch_data(url)
        if not html_data:
            return [("SYSTEM", f"No profile comments found on page {page}.", "0", "N/A", False)]

        parser = ProfileCommentParser()
        parser.feed(html_data)
        return parser.comments if parser.comments else [("SYSTEM", f"No comments on page {page}.", "0", "N/A", False)]

    elif mode == "studio" and studio_id:
        url = f"https://scratch.mit.edu/site-api/comments/gallery/{studio_id}/?page={page}"
        html_data = fetch_data(url)
        if not html_data:
            return [("SYSTEM", f"No studio comments found on page {page}.", "0", "N/A", False)]

        parser = StudioCommentParser()
        parser.feed(html_data)
        return parser.comments if parser.comments else [("SYSTEM", f"No comments on page {page}.", "0", "N/A", False)]

    elif mode == "project" and project_id:
        url = f"https://api.scratch.mit.edu/users/{username}/projects/{project_id}/comments?limit=10&offset={(page-1)*10}"
        raw_json = fetch_data(url)
        if not raw_json:
            return [("SYSTEM", f"No comments or project unreachable (Page {page}).", "0", "N/A", False)]

        try:
            data = json.loads(raw_json)
            if not isinstance(data, list) or not data:
                return [("SYSTEM", f"No comments on page {page}.", "0", "N/A", False)]

            comments = []
            for c in data:
                c_id = str(c.get('id', '0'))
                author = c.get('author', {}).get('username', 'Unknown')
                content = " ".join(c.get('content', '').split())
                created_time = format_timestamp(c.get('datetime_created', ''))
                comments.append((author, content, c_id, created_time, False))

                # Fetch replies
                replies_url = f"https://api.scratch.mit.edu/users/{username}/projects/{project_id}/comments/{c_id}/replies"
                replies_raw = fetch_data(replies_url)
                if replies_raw:
                    replies_data = json.loads(replies_raw)
                    if isinstance(replies_data, list):
                        for r in replies_data:
                            r_id = str(r.get('id', '0'))
                            r_author = r.get('author', {}).get('username', 'Unknown')
                            r_content = " ".join(r.get('content', '').split())
                            r_time = format_timestamp(r.get('datetime_created', ''))
                            comments.append((r_author, r_content, r_id, r_time, True))

            return comments
        except Exception as e:
            return [("SYSTEM", f"JSON Parse Error: {e}", "0", "N/A", False)]

    return [("SYSTEM", "Select a valid target via [P] or [S]", "0", "N/A", False)]

def fetch_user_profile(username):
    user_url = f"https://api.scratch.mit.edu/users/{username}"
    sdb_url = f"https://scratchdb.lefty.one/v3/user/info/{username}"

    user_raw = fetch_data(user_url)
    if not user_raw:
        return None

    try:
        data = json.loads(user_raw)

        # Try ScratchDB for exact follower/following counts
        sdb_raw = fetch_data(sdb_url)
        sdb_followers = None
        sdb_following = None
        if sdb_raw:
            try:
                sdb_data = json.loads(sdb_raw)
                sdb_followers = sdb_data.get('statistics', {}).get('followers')
                sdb_following = sdb_data.get('statistics', {}).get('following')
            except Exception:
                pass

        # Fallback to API if ScratchDB is down or unindexed
        if sdb_followers is None:
            followers_raw = fetch_data(f"https://api.scratch.mit.edu/users/{username}/followers?limit=40")
            sdb_followers = len(json.loads(followers_raw)) if followers_raw else "N/A"

        if sdb_following is None:
            following_raw = fetch_data(f"https://api.scratch.mit.edu/users/{username}/following?limit=40")
            sdb_following = len(json.loads(following_raw)) if following_raw else "N/A"

        data['stats'] = {
            'following': sdb_following,
            'followers': sdb_followers
        }
        return data
    except Exception:
        return None

def fetch_user_projects(username):
    url = f"https://api.scratch.mit.edu/users/{username}/projects?limit=40"
    raw_json = fetch_data(url)
    return json.loads(raw_json) if raw_json else []

def display_profile_inspector(stdscr, username, width, height):
    stdscr.clear()
    stdscr.addstr(0, 0, f"=== User Inspector: @{username} ===", curses.color_pair(2) | curses.A_BOLD)
    stdscr.addstr(1, 0, "Fetching profile data...", curses.A_DIM)
    stdscr.refresh()

    data = fetch_user_profile(username)

    if not data:
        stdscr.clear()
        stdscr.addstr(0, 0, f"=== User Inspector: @{username} ===", curses.color_pair(2) | curses.A_BOLD)
        stdscr.addstr(2, 0, "Failed to load user info or user does not exist.")
        stdscr.addstr(height - 1, 0, " Press any key to return... ", curses.color_pair(3))
        stdscr.refresh()
        stdscr.getch()
        return

    profile = data.get('profile', {})
    history = data.get('history', {})
    stats = data.get('stats', {})

    joined = format_timestamp(history.get('joined', ''))
    country = profile.get('country', 'Not specified')
    scratcher = "Yes" if data.get('scratchteam', False) else "No"

    bio = profile.get('bio', 'None')
    status = profile.get('status', 'None')

    # Prepare formatted lines buffer
    raw_lines = [
        f"User ID:      {data.get('id', 'N/A')}",
        f"Joined:       {joined}",
        f"Country:      {country}",
        f"Scratch Team: {scratcher}",
        f"Followers:    {stats.get('followers', 'N/A')}  |  Following: {stats.get('following', 'N/A')}",
        "-" * (width - 4),
        "[ About Me ]",
        bio,
        "",
        "[ What I'm Working On ]",
        status
    ]

    formatted_buffer = []
    for line in raw_lines:
        if line.startswith("[") or line.startswith("User") or line.startswith("Joined") or line.startswith("Country") or line.startswith("Scratch") or line.startswith("Followers") or line.startswith("-"):
            formatted_buffer.append((line, True))
        else:
            # Wrap long body text paragraphs cleanly
            words = line.split(" ")
            curr_line = ""
            for w in words:
                if len(curr_line) + len(w) + 1 < width - 2:
                    curr_line += w + " "
                else:
                    formatted_buffer.append((curr_line, False))
                    curr_line = w + " "
            if curr_line:
                formatted_buffer.append((curr_line, False))

    # Scrollable loop inside inspector view
    inspect_offset = 0
    max_visible = height - 3

    while True:
        stdscr.clear()
        stdscr.addstr(0, 0, f"=== User Inspector: @{username} ===", curses.color_pair(2) | curses.A_BOLD)

        visible = formatted_buffer[inspect_offset:inspect_offset + max_visible]
        for idx, (text, is_header) in enumerate(visible):
            attr = (curses.color_pair(1) | curses.A_BOLD) if is_header else curses.A_NORMAL
            try:
                stdscr.addstr(idx + 1, 0, text[:width-1], attr)
            except curses.error:
                pass

        footer_text = f" [↑/↓]: Scroll Bio | Total Lines: {len(formatted_buffer)} | Press [Q] or [Esc] to exit "
        try:
            stdscr.addstr(height - 1, 0, footer_text[:width-1], curses.color_pair(3))
        except curses.error:
            pass

        stdscr.refresh()
        key = stdscr.getch()

        if key in (27, ord('q'), ord('Q'), ord('i'), ord('I')): # Esc, Q, or I exits
            break
        elif key in (curses.KEY_DOWN, ord('j'), ord('J')):
            if inspect_offset < max(0, len(formatted_buffer) - max_visible):
                inspect_offset += 1
        elif key in (curses.KEY_UP, ord('k'), ord('K')):
            if inspect_offset > 0:
                inspect_offset -= 1

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

    if curses.has_colors():
        curses.init_pair(1, curses.COLOR_CYAN, -1)   # Parent Author
        curses.init_pair(2, curses.COLOR_YELLOW, -1) # Header
        curses.init_pair(3, curses.COLOR_GREEN, -1)  # Footer / Status
        curses.init_pair(4, curses.COLOR_MAGENTA, -1)# Reply Author
        curses.init_pair(5, curses.COLOR_BLUE, -1)   # Timestamps

    username = "griffpatch"
    mode = "profile"
    project_id = None
    project_title = ""
    studio_id = None
    current_page = 1
    scroll_offset = 0
    search_query = ""
    auto_reload = False

    comments = fetch_comments(username, mode, current_page, project_id, studio_id)

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

        # Header
        if mode == "profile":
            target_info = f"@{username}"
        elif mode == "project":
            target_info = f"@{username} -> Proj: {project_id} ({project_title[:15]})"
        else: # studio
            target_info = f"Studio: {studio_id}"

        filter_info = f" | FIND: '{search_query}'" if search_query else ""
        header = f" === COMMENTINATOR | Mode: {mode.upper()} | {target_info} | PG {current_page}{filter_info} === "
        stdscr.addstr(0, 0, header[:width-1], curses.color_pair(2) | curses.A_BOLD)

        # Apply search filter if active
        active_comments = comments
        if search_query:
            q = search_query.lower()
            active_comments = [c for c in comments if q in c[0].lower() or q in c[1].lower()]

        # Rendering line buffer
        display_lines = []
        for author, content, c_id, c_time, is_reply in active_comments:
            prefix = "  ↳ " if is_reply else ""
            indent = "    " if is_reply else "  "
            color = curses.color_pair(4) if is_reply else curses.color_pair(1)

            # Author line with ID & Time
            meta_str = f"{prefix}@{author}  [ID: {c_id}]  ({c_time})"
            display_lines.append((meta_str, color | curses.A_BOLD))

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

            display_lines.append(("", curses.A_NORMAL))

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

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

        # Footer
        auto_status = "ON" if auto_reload else "OFF"
        status = f" [←/→]: Pg | [/]: Find | [R]eload | [Y] Auto: {auto_status} | [I]nspect | [M]ode | [U]ser | [Q]uit "
        try:
            stdscr.addstr(height - 1, 0, status[:width-1], curses.color_pair(3))
        except curses.error:
            pass

        stdscr.refresh()

        # Set input timeout to 1000ms (1 second) if auto_reload is active, else block (-1)
        stdscr.timeout(1000 if auto_reload else -1)
        key = stdscr.getch()

        # Handle timeout event (auto-reload tick)
        if key == curses.ERR:
            if auto_reload:
                comments = fetch_comments(username, mode, current_page, project_id, studio_id)
            continue

        if key in (ord('q'), ord('Q')):
            break

        # Inspector View [I]
        elif key in (ord('i'), ord('I')):
            display_profile_inspector(stdscr, username, width, height)

        # Search / Find [ / ]
        elif key == ord('/'):
            curses.echo()
            curses.curs_set(1)
            stdscr.addstr(height - 1, 0, "Find text/user (Enter to clear): ".ljust(width-1), curses.color_pair(2))
            stdscr.refresh()
            search_query = stdscr.getstr(height - 1, 33, 32).decode('utf-8').strip()
            curses.noecho()
            curses.curs_set(0)
            scroll_offset = 0

        # Reload / Refresh [R]
        elif key in (ord('r'), ord('R')):
            scroll_offset = 0
            comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        # Toggle Auto-Reload [Y]
        elif key in (ord('y'), ord('Y')):
            auto_reload = not auto_reload

        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:
            current_page += 1
            scroll_offset = 0
            comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        elif key == curses.KEY_LEFT:
            if current_page > 1:
                current_page -= 1
                scroll_offset = 0
                comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        elif key in (ord('j'), ord('J')):
            current_page += 10
            scroll_offset = 0
            comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        elif key in (ord('l'), ord('L')):
            current_page = max(1, current_page - 10)
            scroll_offset = 0
            comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        elif key in (ord('m'), ord('M')):
            if mode == "profile":
                mode = "project" if project_id else "studio"
            elif mode == "project":
                mode = "studio" if studio_id else "profile"
            else:
                mode = "profile"
            current_page = 1
            scroll_offset = 0
            comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        elif key in (ord('u'), ord('U')):
            curses.echo()
            curses.curs_set(1)
            stdscr.addstr(height - 1, 0, "Enter Username: ".ljust(width-1), curses.color_pair(2))
            stdscr.refresh()
            new_user = stdscr.getstr(height - 1, 16, 32).decode('utf-8').strip()
            curses.noecho()
            curses.curs_set(0)

            if new_user:
                username = new_user
                project_id = None
                project_title = ""
                mode = "profile"
                current_page = 1
                scroll_offset = 0
                search_query = ""
                comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        # Studio Direct Select [S]
        elif key in (ord('s'), ord('S')):
            curses.echo()
            curses.curs_set(1)
            stdscr.addstr(height - 1, 0, "Enter Studio ID (Default 5338610): ".ljust(width-1), curses.color_pair(2))
            stdscr.refresh()
            input_studio = stdscr.getstr(height - 1, 35, 32).decode('utf-8').strip()
            curses.noecho()
            curses.curs_set(0)

            studio_id = input_studio if input_studio else "5338610"
            mode = "studio"
            current_page = 1
            scroll_offset = 0
            search_query = ""
            comments = fetch_comments(username, mode, current_page, project_id, studio_id)

        elif key in (ord('p'), ord('P')):
            stdscr.clear()
            stdscr.addstr(0, 0, f"Fetching projects for @{username}...", curses.color_pair(2))
            stdscr.refresh()
            projects = fetch_user_projects(username)

            stdscr.clear()
            stdscr.addstr(0, 0, f"=== Projects for @{username} ===", curses.color_pair(2) | curses.A_BOLD)

            if not projects:
                stdscr.addstr(2, 0, "No public projects found. Press any key...")
                stdscr.getch()
            else:
                for idx, p in enumerate(projects[:max_visible_lines - 2], 1):
                    p_info = f"[{idx}] ID: {p['id']} | {p['title']} (Views: {p.get('stats', {}).get('views', 0)})"
                    stdscr.addstr(idx + 1, 0, p_info[:width-1])

                stdscr.addstr(height - 1, 0, "Select Index # or paste Project ID: ", curses.color_pair(3))
                curses.echo()
                curses.curs_set(1)
                choice = stdscr.getstr(height - 1, 35, 32).decode('utf-8').strip()
                curses.noecho()
                curses.curs_set(0)

                if choice.isdigit():
                    num = int(choice)
                    if 1 <= num <= len(projects):
                        project_id = str(projects[num - 1]['id'])
                        project_title = projects[num - 1]['title']
                    else:
                        project_id = choice
                        project_title = "Direct ID"
                elif choice:
                    project_id = choice
                    project_title = "Direct ID"

                if project_id:
                    mode = "project"
                    current_page = 1
                    scroll_offset = 0
                    search_query = ""
                    comments = fetch_comments(username, mode, current_page, project_id, studio_id)

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