"""Stage 9: Heap / Priority Queue (problems 81-87)."""
from __future__ import annotations

import heapq
import itertools
from collections import Counter, defaultdict
from typing import List


class KthLargest:
    """LC 703. Keep a min-heap of size k; its top is the k-th largest."""

    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.heap = heapq.nlargest(k, nums)
        heapq.heapify(self.heap)

    def add(self, val: int) -> int:
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        return self.heap[0]


def last_stone_weight(stones: List[int]) -> int:
    """LC 1046. Python only has a min-heap, so store negated weights."""
    heap = [-s for s in stones]
    heapq.heapify(heap)
    while len(heap) > 1:
        a, b = -heapq.heappop(heap), -heapq.heappop(heap)
        if a != b:
            heapq.heappush(heap, -(a - b))
    return -heap[0] if heap else 0


def k_closest(points: List[List[int]], k: int) -> List[List[int]]:
    """LC 973. nsmallest by squared distance (no square root needed)."""
    return heapq.nsmallest(k, points, key=lambda p: p[0] * p[0] + p[1] * p[1])


def find_kth_largest(nums: List[int], k: int) -> int:
    """LC 215. Min-heap of size k: O(n log k)."""
    heap: List[int] = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)
    return heap[0]


def least_interval(tasks: List[str], n: int) -> int:
    """LC 621. Frame by the most frequent task: (maxCount - 1) * (n + 1) + tasksWithMaxCount."""
    counts = Counter(tasks).values()
    top = max(counts)
    with_top = sum(1 for c in counts if c == top)
    return max(len(tasks), (top - 1) * (n + 1) + with_top)


class Twitter:
    """LC 355. Merge the followees' recent tweets with a heap (k-way merge, stop at 10)."""

    def __init__(self) -> None:
        self.clock = itertools.count()
        self.tweets = defaultdict(list)  # user -> [(time, tweetId)]
        self.follows = defaultdict(set)

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweets[userId].append((next(self.clock), tweetId))

    def getNewsFeed(self, userId: int) -> List[int]:
        users = self.follows[userId] | {userId}
        heap = []
        for u in users:
            if self.tweets[u]:
                i = len(self.tweets[u]) - 1
                t, tid = self.tweets[u][i]
                heap.append((-t, tid, u, i))
        heapq.heapify(heap)
        feed: List[int] = []
        while heap and len(feed) < 10:
            _, tid, u, i = heapq.heappop(heap)
            feed.append(tid)
            if i > 0:
                t, nxt = self.tweets[u][i - 1]
                heapq.heappush(heap, (-t, nxt, u, i - 1))
        return feed

    def follow(self, followerId: int, followeeId: int) -> None:
        if followerId != followeeId:
            self.follows[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.follows[followerId].discard(followeeId)


class MedianFinder:
    """LC 295. Max-heap for the lower half, min-heap for the upper half, sizes differ by <= 1."""

    def __init__(self) -> None:
        self.low: List[int] = []   # negated values (max-heap)
        self.high: List[int] = []  # min-heap

    def addNum(self, num: int) -> None:
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def findMedian(self) -> float:
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2
