from pathlib import Path

TASKS_FILE = Path("tasks.txt")


def load_tasks():
    """Read saved tasks, one per line (empty list if there's no file yet)."""
    if TASKS_FILE.exists():
        return [line for line in TASKS_FILE.read_text().splitlines() if line]
    return []


def save_tasks(tasks):
    TASKS_FILE.write_text("\n".join(tasks))


def show_tasks(tasks):
    if not tasks:
        print("(no tasks yet)")
        return
    for number, task in enumerate(tasks, start=1):
        print(f"{number}. {task}")


def add_task(tasks):
    text = input("New task: ").strip()
    if text:
        tasks.append(text)
        print(f"Added: {text}")
    else:
        print("Nothing to add.")


def remove_task(tasks):
    show_tasks(tasks)
    raw = input("Remove which number? ").strip()
    try:
        index = int(raw) - 1
    except ValueError:
        print("Please type a number.")
        return
    if 0 <= index < len(tasks):
        print(f"Removed: {tasks.pop(index)}")
    else:
        print("No task with that number.")


def main():
    tasks = load_tasks()
    menu = "\n[a]dd  [l]ist  [r]emove  [q]uit\n> "
    while True:
        choice = input(menu).strip().lower()
        if choice == "a":
            add_task(tasks)
        elif choice == "l":
            show_tasks(tasks)
        elif choice == "r":
            remove_task(tasks)
        elif choice == "q":
            save_tasks(tasks)
            print("Saved. Bye!")
            break
        else:
            print("Unknown option, use a, l, r, or q.")


if __name__ == "__main__":
    main()
