"""Original Lawfare Academy lab: indexes, duplicate records, BFS and Dijkstra.
Run with Python 3. No external dependencies. All graphs are fictional.
"""
from collections import deque
from heapq import heappush, heappop

def index_rows(rows):
    result = {}
    for row in rows:
        result.setdefault(row['customer'], []).append(row['id'])
    return result

def linear_ids(rows, customer):
    return [row['id'] for row in rows if row['customer'] == customer]

def bfs(graph, start, target):
    queue, parent = deque([start]), {start: None}
    while queue:
        node = queue.popleft()
        if node == target:
            route = []
            while node is not None:
                route.append(node)
                node = parent[node]
            return list(reversed(route))
        for neighbor, cost in graph.get(node, []):
            if neighbor not in parent:
                parent[neighbor] = node
                queue.append(neighbor)
    return None

def dijkstra(graph, start, target):
    for edges in graph.values():
        if any(cost < 0 for _, cost in edges):
            raise ValueError('Nonnegative costs required')
    pending, best = [(0, start, [start])], {start: 0}
    while pending:
        cost, node, route = heappop(pending)
        if cost != best[node]:
            continue
        if node == target:
            return cost, route
        for neighbor, weight in graph.get(node, []):
            proposed = cost + weight
            if proposed < best.get(neighbor, float('inf')):
                best[neighbor] = proposed
                heappush(pending, (proposed, neighbor, route + [neighbor]))
    return None

def main():
    rows = [{'id': i, 'customer': str(i % 7)} for i in range(100)]
    idx = index_rows(rows)
    for key in [str(i) for i in range(10)]:
        assert idx.get(key, []) == linear_ids(rows, key)
    rows.append({'id': 100, 'customer': '0'})
    assert idx['0'] != linear_ids(rows, '0')  # stale index exposed
    idx = index_rows(rows)
    assert idx['0'] == linear_ids(rows, '0')
    graph = {'A': [('C', 100), ('B', 1)], 'B': [('C', 1)], 'C': [('A', 1)]}
    assert bfs(graph, 'A', 'C') == ['A', 'C']
    assert dijkstra(graph, 'A', 'C') == (2, ['A', 'B', 'C'])
    assert dijkstra(graph, 'A', 'missing') is None
    assert dijkstra(graph, 'A', 'A') == (0, ['A'])
    print('PASS: scan/index equivalence, stale-index detection, cycles, absent nodes and weighted-search counterexample')

if __name__ == '__main__':
    main()
