#!/usr/bin/python3

"""Extract nearest url.

for use in vim: gx - openurlundercursor function

---
source: https://github.com/sderev/vim-url-opener
"""

import re
import sys


def main():
    line = " ".join(sys.argv[1:-1]) if len(sys.argv) > 1 else ""
    try:
        cursor_pos = int(sys.argv[-1])
    except ValueError:
        sys.exit("Error: Cursor position must be an integer")
    url = extract_nearest_url(line, cursor_pos)
    print(url, end="")  # print without additional newline


def extract_nearest_url(line, cursor_pos):
    # regular expression to extract URLs
    url_patterns = (
        r"\[.*?\]\((\S+?)\)",  # markdown link
        r"<(\S+?)>",  # angle brackets
        r"\\href\{(\S+?)\}\{.*?\}",  # LaTeX \href{}{}
        r"(http[s]?://\S+)",  # plain URLs with protocol
        r'(?:src|href|content)=["\'](.*?)["\']',  # HTML/XML attributes
    )
    pattern = "|".join(url_patterns)
    matches = re.finditer(pattern, line)

    nearest_url = None
    min_distance = float("inf")

    # extract URL
    for match in matches:
        url = next((group for group in match.groups() if group), None)

        # calculate distances to cursor position
        start_pos = match.start()
        end_pos = match.end()
        distance = min(abs(cursor_pos - start_pos), abs(cursor_pos - end_pos))

        # update nearest URL
        if distance < min_distance:
            min_distance = distance
            # clean the URL by removing any trailing punctuation and whitespace
            cleaned_url = re.sub(r"[\"),.\s]*$", "", url)
            nearest_url = cleaned_url

    return nearest_url if nearest_url else ""


if __name__ == "__main__":
    main()
