"""Jalankan: python app.py. Data berada di samping file program."""
from pathlib import Path
import core

DATA = Path(__file__).with_name("tasks.json")


def main():
    try:
        rows = core.load(DATA)
    except (ValueError, OSError) as error:
        print("Data tidak dapat dibuka; file dipertahankan:", error)
        return
    while True:
        print("\n1 Daftar | 2 Tambah | 3 Cari | 4 Selesai | 5 Simpan | 0 Keluar")
        choice = input("Pilihan: ").strip()
        try:
            if choice in ("1", "3"):
                found = rows if choice == "1" else core.search(rows, input("Kata judul: "))
                for row in found:
                    print(row["id"], "[x]" if row["done"] else "[ ]", row["title"])
                if not found:
                    print("Tidak ada tugas.")
                print("Selesai / total:", core.summary(rows))
            elif choice == "2":
                core.add(rows, input("Judul: "))
            elif choice == "4":
                core.complete(rows, int(input("ID tugas: ")))
            elif choice == "5":
                core.save(DATA, rows)
                print("Tersimpan:", DATA)
            elif choice == "0":
                if input("Simpan sebelum keluar? y/n: ").strip().lower() == "y":
                    core.save(DATA, rows)
                break
            else:
                print("Pilih menu yang tersedia.")
        except (ValueError, OSError) as error:
            print("Belum berhasil:", error)


if __name__ == "__main__":
    main()
