"""
Checks your answers in exercises.py.

  uv run check.py              check everything
  uv run check.py 7 12         check only exercises 7 and 12
  uv run check.py --solutions  check solutions.py instead
"""

import importlib
import os
import sys
import tempfile

args = sys.argv[1:]
module_name = "solutions" if "--solutions" in args else "exercises"
only = {int(a) for a in args if a.isdigit()}
ex = importlib.import_module(module_name)

TESTS = []


def test(fn):
    TESTS.append(fn)
    return fn


def eq(actual, expected, label=""):
    if actual != expected:
        where = f"{label}: " if label else ""
        raise AssertionError(f"{where}expected {expected!r}, got {actual!r}")


def temp_file(content):
    fd, path = tempfile.mkstemp(suffix=".txt")
    with os.fdopen(fd, "w") as f:
        f.write(content)
    return path


# --- Part 1 ---------------------------------------------------------------

@test
def greet():
    eq(ex.greet("Ana", 3), ["Hi Ana", "Hi Ana", "Hi Ana"])
    eq(ex.greet("Bo", 0), [])

@test
def count_positive():
    eq(ex.count_positive([3, -1, 0, 5]), 2)
    eq(ex.count_positive([]), 0)

@test
def squares_of_evens():
    eq(ex.squares_of_evens([1, 2, 3, 4]), [4, 16])
    eq(ex.squares_of_evens([1, 3]), [])

@test
def index_of_max():
    eq(ex.index_of_max([3, 9, 2, 9]), 1)
    eq(ex.index_of_max([-5]), 0)
    eq(ex.index_of_max([]), None)

@test
def pair_up():
    eq(ex.pair_up(["ana", "bo"], [90, 85]), {"ana": 90, "bo": 85})
    eq(ex.pair_up(["a", "b", "c"], [1]), {"a": 1}, "uneven lists")

@test
def first_and_rest():
    eq(ex.first_and_rest([1, 2, 3]), (1, [2, 3]))
    eq(ex.first_and_rest([7]), (7, []))
    eq(ex.first_and_rest([]), (None, []))

@test
def swap_ends():
    original = [1, 2, 3, 4]
    eq(ex.swap_ends(original), [4, 2, 3, 1])
    eq(original, [1, 2, 3, 4], "original list must not change")
    eq(ex.swap_ends([1]), [1])
    eq(ex.swap_ends([]), [])

# --- Part 2 ---------------------------------------------------------------

@test
def reverse_string():
    eq(ex.reverse_string("hello"), "olleh")
    eq(ex.reverse_string(""), "")

@test
def is_palindrome():
    eq(ex.is_palindrome("A man, a plan, a canal: Panama"), True)
    eq(ex.is_palindrome("hello"), False)
    eq(ex.is_palindrome(""), True)

@test
def every_other():
    eq(ex.every_other([1, 2, 3, 4, 5]), [1, 3, 5])
    eq(ex.every_other([]), [])

@test
def last_n():
    eq(ex.last_n([1, 2, 3, 4, 5], 2), [4, 5])
    eq(ex.last_n([1, 2, 3], 0), [], "n=0")
    eq(ex.last_n([1, 2, 3], 10), [1, 2, 3], "n bigger than the list")

@test
def chunk():
    eq(ex.chunk([1, 2, 3, 4, 5], 2), [[1, 2], [3, 4], [5]])
    eq(ex.chunk([], 3), [])

# --- Part 3 ---------------------------------------------------------------

@test
def word_count():
    eq(ex.word_count("the cat The hat"), {"the": 2, "cat": 1, "hat": 1})
    eq(ex.word_count(""), {})

@test
def group_by_length():
    eq(ex.group_by_length(["hi", "yo", "cat", "a"]), {2: ["hi", "yo"], 3: ["cat"], 1: ["a"]})
    eq(ex.group_by_length([]), {})

@test
def common_items():
    eq(ex.common_items([3, 1, 2, 2], [2, 3, 4]), [2, 3])
    eq(ex.common_items([1], [2]), [])

@test
def dedupe_keep_order():
    eq(ex.dedupe_keep_order([3, 1, 3, 2, 1]), [3, 1, 2])
    eq(ex.dedupe_keep_order(["b", "a", "b"]), ["b", "a"])

@test
def invert_dict():
    eq(ex.invert_dict({"a": 1, "b": 2}), {1: "a", 2: "b"})

# --- Part 4 ---------------------------------------------------------------

@test
def add_item():
    eq(ex.add_item("x"), ["x"], "first call")
    eq(ex.add_item("y"), ["y"], "second call (should get a fresh list)")
    mine = []
    ex.add_item("z", mine)
    eq(mine, ["z"], "a list you pass in (even an empty one) should be appended to")

@test
def make_counter():
    c = ex.make_counter()
    eq([c(), c(), c()], [1, 2, 3])
    d = ex.make_counter()
    eq(d(), 1, "a second counter starts from 1")

@test
def apply_all():
    eq(ex.apply_all(3, lambda x: x + 1, lambda x: x * 10), 40)
    eq(ex.apply_all(5), 5)

@test
def build_url():
    eq(ex.build_url("https://x.com/search", q="cats", page=2), "https://x.com/search?q=cats&page=2")
    eq(ex.build_url("https://x.com"), "https://x.com")

# --- Part 5 ---------------------------------------------------------------

@test
def point():
    P = ex.Point
    eq(P(0, 0).distance_to(P(3, 4)), 5.0)
    eq(P(1, 2) == P(1, 2), True, "equality")
    eq(len({P(1, 2), P(1, 2)}), 1, "usable in a set")
    eq(repr(P(1, 2)), "Point(x=1, y=2)", "repr")

@test
def stack():
    s = ex.Stack()
    eq(len(s), 0)
    eq(bool(s), False, "empty stack is falsy")
    s.push(1)
    s.push(2)
    eq(s.peek(), 2)
    eq(len(s), 2)
    eq(s.pop(), 2)
    eq(s.pop(), 1)
    try:
        s.pop()
    except IndexError:
        pass
    else:
        raise AssertionError("pop() on an empty stack should raise IndexError")

# --- Part 6 ---------------------------------------------------------------

@test
def safe_int():
    eq(ex.safe_int("42"), 42)
    eq(ex.safe_int("abc"), 0)
    eq(ex.safe_int("abc", default=-1), -1)
    eq(ex.safe_int(None), 0, "None")

@test
def count_lines():
    eq(ex.count_lines(temp_file("a\nb\nc\n")), 3)
    eq(ex.count_lines(temp_file("")), 0, "empty file")

@test
def longest_line():
    eq(ex.longest_line(temp_file("short\nthe longest one\nmid\n")), "the longest one")
    eq(ex.longest_line(temp_file("")), "", "empty file")

@test
def describe():
    eq(ex.describe(None), "nothing")
    eq(ex.describe(5), "number 5")
    eq(ex.describe("hi"), "text 'hi'")
    eq(ex.describe([]), "empty list")
    eq(ex.describe([7]), "one item: 7")
    eq(ex.describe([1, 2, 3]), "list starting with 1")
    eq(ex.describe({"x": 1}), "something else")


# --- Runner ---------------------------------------------------------------

def main():
    passed = todo = 0
    selected = [(i, t) for i, t in enumerate(TESTS, 1) if not only or i in only]
    print(f"Checking {module_name}.py\n")
    for i, t in selected:
        name = t.__name__
        try:
            t()
        except NotImplementedError:
            todo += 1
            print(f"  ⬜ {i:2}. {name}")
        except AssertionError as e:
            print(f"  ❌ {i:2}. {name}  ->  {e}")
        except Exception as e:
            print(f"  💥 {i:2}. {name}  ->  {type(e).__name__}: {e}")
        else:
            passed += 1
            print(f"  ✅ {i:2}. {name}")
    print(f"\n{passed}/{len(selected)} passing, {todo} not started")


if __name__ == "__main__":
    main()
