#!/usr/bin/env python3

import sys
from datetime import datetime
import re

MAX_URLS = 1000

def process_bold(text):
    # Convert bold(text) → <b>text</b>
    return re.sub(r'bold\((.*?)\)', r'<b>\1</b>', text)

def get_inputs():
    urls = []

    # Case 1: URLs passed via command line
    if len(sys.argv) > 1:
        for i, url in enumerate(sys.argv[1:], start=1):
            if i > MAX_URLS:
                break
            label = input(f"Enter clickable text for URL {i}: ")
            urls.append((process_bold(label), url))

    # Case 2: Read from stdin
    else:
        count = 0
        for line in sys.stdin:
            if count >= MAX_URLS:
                break

            matches = re.findall(r'"(.*?)"', line)
            if len(matches) >= 2:
                label = process_bold(matches[0])
                url = matches[1]
                urls.append((label, url))
                count += 1

    return urls


def generate_html(entries):
    now = datetime.now()
    date_str = now.strftime("%Y-%m-%d")
    time_str = now.strftime("%H:%M:%S")

    html = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Favorite URLs</title>
</head>
<body>
<pre>
This index.html file was created
    On:   {date_str}
    At:   {time_str}
    Using: clickableFavoriteURLs
Click file name to Download

</pre>
<hr>
"""

    for i, (label, url) in enumerate(entries, start=1):
        html += f"{i:04d} <a href=\"{url}\" target=\"_blank\">{label}</a> {url}<br>\n"

    html += """
</body>
</html>
"""
    return html


def main():
    entries = get_inputs()

    if not entries:
        print("No valid input provided.")
        sys.exit(1)

    html_content = generate_html(entries)

    with open("index.html", "w") as f:
        f.write(html_content)

    print("index.html created successfully.")


if __name__ == "__main__":
    main()
