#!/usr/bin/env python3

# This project is licensed under the Blue Oak Model License 1.0.0.
# See: https://blueoakcouncil.org/license/1.0.0

# Version 1.0 : initial release (09may2025)
# The Spartan Bookmark Launcher (sbl)

# Supported Help Flags: -h  --h  -help  --help  -?  /?

# Install:   chmod +x sbl && sudo install sbl /usr/local/bin
# Uninstall: sudo rm /usr/local/bin/sbl

import sys
import os
import subprocess

def show_help():
    script_name = os.path.basename(sys.argv[0])
    print(f"""
Spartan Bookmark Launcher
=========================

Launch Spartan URLS from a plain text bookmark file. This script uses 'The
Spartan Viewer' (sv) to view and render Gemtext pages at Spartan URLS.

Usage: sbl 

The bookmark file should contain one bookmark per line in this format:

  Page Title: spartan://example.com
  Another Title: spartan://example.com/page.gmi

This script will automatically align the Page Title and URLs. Selecting a
number will launch that URL as "sv spartan://example.com | less -R". After
viewing the page, the script will return you to the bookmark list.

Requires: The Spartan Viewer (sv)
          https://640kb.neocities.org/spartanware/spartanviewer.html
          finger spartanviewer@happynetbox.com
""")

def read_bookmarks(filename):
    bookmarks = []
    try:
        with open(filename) as f:
            for line in f:
                if ':' in line:
                    title, url = line.split(':', 1)
                    title = title.strip()
                    url = url.strip()
                    if url.startswith("spartan://"):
                        bookmarks.append((title, url))
    except FileNotFoundError:
        print(f"File not found: {filename}")
        sys.exit(1)
    return bookmarks

def display_bookmarks(bookmarks):
    os.system('clear')  # Clear the screen for a clean view
    longest = max(len(title) for title, _ in bookmarks)
    print("=" * (longest + 35))
    print("SPARTAN BOOKMARK MANAGER".center(longest + 35))
    print("=" * (longest + 35))
    for idx, (title, url) in enumerate(bookmarks, 1):
        print(f"[{idx:2}] {title.ljust(longest)}  {url}")
    print()

def main():
    help_flags = {'-h', '--h', '-help', '--help', '-?', '/?'}

    if len(sys.argv) != 2 or sys.argv[1].lower() in help_flags:
        show_help()
        sys.exit(0)

    filename = sys.argv[1]
    bookmarks = read_bookmarks(filename)

    if not bookmarks:
        print("No valid bookmarks found.")
        sys.exit(1)

    while True:
        display_bookmarks(bookmarks)
        try:
            choice = input("Enter number to open (0 to quit): ").strip()
            if choice == '0':
                break
            index = int(choice) - 1
            if 0 <= index < len(bookmarks):
                url = bookmarks[index][1]
                subprocess.run(f"sv {url} | less -R", shell=True)
            else:
                print("Invalid choice.")
                input("Press Enter to continue...")
        except ValueError:
            print("Invalid input.")
            input("Press Enter to continue...")
        except KeyboardInterrupt:
            print("\nCanceled.")
            break

if __name__ == "__main__":
    main()