"""Stage 7: Linked List (problems 54-64)."""
from __future__ import annotations

import heapq
from collections import OrderedDict
from typing import List, Optional

from .structures import ListNode, RandomNode


def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]:
    """LC 206. Three pointers: prev, curr, next."""
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev


def merge_two_lists(a: Optional[ListNode], b: Optional[ListNode]) -> Optional[ListNode]:
    """LC 21. Dummy head removes the empty-list special case."""
    dummy = tail = ListNode()
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next


def has_cycle(head: Optional[ListNode]) -> bool:
    """LC 141. Floyd: a fast pointer laps a slow one only if there is a cycle."""
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            return True
    return False


def reorder_list(head: Optional[ListNode]) -> None:
    """LC 143. Find middle, reverse second half, weave the halves together."""
    if not head or not head.next:
        return
    slow, fast = head, head.next
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    second = reverse_list(slow.next)
    slow.next = None
    first = head
    while second:
        first.next, first = second, first.next
        second.next, second = first, second.next


def remove_nth_from_end(head: Optional[ListNode], n: int) -> Optional[ListNode]:
    """LC 19. Give the lead pointer an n-step head start; then move both together."""
    dummy = ListNode(0, head)
    lead = trail = dummy
    for _ in range(n + 1):
        lead = lead.next
    while lead:
        lead, trail = lead.next, trail.next
    trail.next = trail.next.next
    return dummy.next


def copy_random_list(head: Optional[RandomNode]) -> Optional[RandomNode]:
    """LC 138. Map old node -> new node in a first pass; wire next/random in a second."""
    clones = {None: None}
    node = head
    while node:
        clones[node] = RandomNode(node.val)
        node = node.next
    node = head
    while node:
        clones[node].next = clones[node.next]
        clones[node].random = clones[node.random]
        node = node.next
    return clones[head]


def add_two_numbers(l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
    """LC 2. Digits are stored in reverse, so add like grade school with a carry."""
    dummy = tail = ListNode()
    carry = 0
    while l1 or l2 or carry:
        total = carry + (l1.val if l1 else 0) + (l2.val if l2 else 0)
        carry, digit = divmod(total, 10)
        tail.next = ListNode(digit)
        tail = tail.next
        l1 = l1.next if l1 else None
        l2 = l2.next if l2 else None
    return dummy.next


def find_duplicate(nums: List[int]) -> int:
    """LC 287. Treat i -> nums[i] as a linked list; the duplicate is the cycle entrance (Floyd)."""
    slow = fast = nums[0]
    while True:
        slow, fast = nums[slow], nums[nums[fast]]
        if slow == fast:
            break
    slow = nums[0]
    while slow != fast:
        slow, fast = nums[slow], nums[fast]
    return slow


class LRUCache:
    """LC 146. Hash map + doubly linked list; OrderedDict gives both in the standard library."""

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.data: OrderedDict = OrderedDict()

    def get(self, key: int) -> int:
        if key not in self.data:
            return -1
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key: int, value: int) -> None:
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)


def merge_k_lists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:
    """LC 23. Min-heap of list heads; index breaks ties so nodes are never compared."""
    heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(heap)
    dummy = tail = ListNode()
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next


def reverse_k_group(head: Optional[ListNode], k: int) -> Optional[ListNode]:
    """LC 25. Check k nodes exist, reverse them, reconnect, repeat from the group's new tail."""
    dummy = ListNode(0, head)
    group_prev = dummy
    while True:
        kth = group_prev
        for _ in range(k):
            kth = kth.next
            if not kth:
                return dummy.next
        group_next = kth.next
        prev, curr = group_next, group_prev.next
        while curr is not group_next:
            curr.next, prev, curr = prev, curr, curr.next
        first = group_prev.next
        group_prev.next = kth
        group_prev = first
