import os
import json
import urllib.request

linkwarden_url = os.environ.get('LINKWARDEN_URL')
linkwarden_token = os.environ.get('LINKWARDEN_TOKEN')

def get_links_part(cursor):
    request = urllib.request.Request(linkwarden_url + "/api/v1/links?sort=0&cursor=" + str(cursor), headers={
        'Authorization': 'Bearer ' + linkwarden_token
    })
    request.timeout = 5
    response = urllib.request.urlopen(request)
    data = response.read().decode("utf-8")
    data = data.replace("\\n", " ").replace("\\r", " ").replace("\\t", " ")
    data = ' '.join(data.split())
    return json.loads(data).get("response", [])

def get_links():
    cursor = 0
    links = []

    while True:
        new_links = get_links_part(cursor)

        links += new_links
        if len(new_links):
            cursor = new_links[-1]["id"]
        else:
            return links

def format_link(link):
    url = link.get("url")
    if not url:
        return None

    for tag in link.get("tags", []):
        if tag.get("name") == "Archived":
            return None
        if tag.get("name") == "Inactive":
            return None

    title = link.get("name")
    if not title:
        title = link.get("description")
    if not title:
        title = "<untitled>"

    collection = link.get("collection", {}).get("name")
    if not collection:
        collection = "<uncategorized>"
        
    return f"{url} {collection}/{title}"

def format_links(links):
    formatted_links = []
    for link in links:
        if f_link := format_link(link):
            formatted_links.append(f_link)
    return formatted_links

def init():
    if linkwarden_url is None or linkwarden_token is None:
        return

    links = format_links(get_links())

    with open(os.path.expanduser("~/.config/qutebrowser/bookmarks/urls"), "w+") as f:
        f.write("\n".join(links))
        f.close()


if __name__ == "__main__":
    if linkwarden_url is None or linkwarden_token is None:
        print("LINKWARDEN_URL and LINKWARDEN_TOKEN environment variables are required.")
        exit(1)

    print("\n".join(format_links(get_links())))