#!/usr/bin/python3
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#-*- coding: utf-8 -*-

# ##########################################################
"""
         FILE: skb
  DESCRIPTION: Search SUSE KB from commandline
      OPTIONS: 
 REQUIREMENTS: 
        NOTES: 
       AUTHOR: Raine Curtis (raine.curtis@suse.com) 
 ORGANIZATION: SUSE
      VERSION: 1.0
      CREATED: 2025-08-11
      UPDATED: 2025-08-15
     REVISION: 1.1
"""
# ##########################################################

import os
import sys
import pydoc
import getopt
import requests
import urllib.parse
#import re
#import html2text as h2t
from bs4 import BeautifulSoup

# Globals
kb_server = "https://www.suse.com"


def get_products():
    product_list = []
    query_str = kb_server  + "/support/kb/"
    page = requests.get(query_str)
    bs = BeautifulSoup(page.content, "html.parser")
    #print(bs.prettify())
    products = bs.find(id="kbproductlist").find_all("option")
    for product in products:
        product = product.text.strip()
        if  'Choose a Product' not in product: 
            if '--Deprecated Products--' not in product:
                product_list.append(product)
    return product_list

def select_product(products):
    i = 0
    while True:
        os.system("clear")
        print("Select a Product:")
        print("0 - None")
        i  = 0
        for product in products:
            i += 1
            print("{} - {}".format(i, product))
        print(" q - Quit")
        print(" b - Back")
        choice = input("Enter the product for the search: ")
        choice = choice.strip()
        if  'q' in choice:
            quit()
        if len(choice) == 0:
            continue
        elif 'b' == choice:
            return 'reset'
        choice = int(choice) - 1
        if choice == 0 or choice == -1:
            return ''
        elif choice > 0 and choice < len(products):
            return  products[choice]


def search_kb(product, search_str=''):
    """ 
    Search KB
    """
    tids  = {}

    URL = "{}/support/kb/?id={}&q={}".format(kb_server, urllib.parse.quote(product), urllib.parse.quote(search_str))
    #print(URL)
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, "html.parser")
    kbs = soup.find("div", class_="result-table").find_all('a')
    i = 0
    for kb in kbs:
        try:
            i += 1
            kb_tid = kb.find('span').text.strip('(').strip(')')
            kb_title = kb.text
            kb_url = kb_server + kb.get('href')
            tid = { i : {
                "kb_tid": kb_tid,
                "kb_title": kb_title,
                "kb_url": kb_url,
                }
            }
            tids.update(tid)
        except Exception as e:
            print("Error processing KB entry {}: {}".format(i, e))
    return tids

def select_tid(tids, product='', search_str=''):
    while True:
        os.system("clear")
        print("skb: Results from SUSE Knowledgebase")
        print('-' * 80)
        print("Product: [{}] \nSearch String: [{}]".format(product, search_str))
        print('-' * 80)
        i = 0
        for t in tids:
            i  += 1
            print("{} - {}".format(i, tids[t]['kb_title']))
        print(" q - Quit")
        print(" b - Back")
        choice = input("Select tid to view: ")
        if  'q' == choice:
            quit()
        elif 'b' == choice:
            return
        if len(choice) == 0:
            continue
        choice = int(choice)

        #print(tids[choice]["kb_url"])
        tid_url = tids[choice]["kb_url"]
        show_tid(tid_url)

def show_tid(tid_url):
    text_doc = ''
    #print(tid_url)
    page = requests.get(tid_url)
    soup = BeautifulSoup(page.content, "html.parser")
    text_doc = soup.find(id='importedcontent').get_text()
    text_doc = text_doc.strip(' ')
    text_doc = text_doc.replace('  ', '')
    text_doc = "TID URL: {}\n {}".format(tid_url, text_doc)
    try:
        pydoc.pipepager(text_doc, 'less -R')
    except Exception as e:
        print("Error displaying TID content: {}".format(e))
        #pass

def get_query_str():
    while True:
        search_str = input("Enter search criteria: ")
        if len(search_str) >  0:
            return search_str


# Command-line start
if __name__ == '__main__':
    print("SUSE Knowledgebase Search Tool (skb v0.1.1)")
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hs:p:l", ["help", "search=", "product=", "listproducts"])
    except getopt.GetoptError as e:
        print("Error parsing options: {}".format(e))
        sys.exit(1)

    if len(args) == 0 and opts == []:
        while True:
            search_str = get_query_str()
            products = get_products()
            product = select_product(products)
            if product == 'reset':
                continue
            tids = search_kb(product, search_str)
            tid = select_tid(tids, product, search_str)
    else:
        search_query = ''
        product_name = ''
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print("Usage: skb [options]")
                print("Options:")
                print("  -h, --help            Show this help message")
                print("  -s, --search <query>  Search for knowledge base articles")
                print("  -p, --product <name>  Specify the product for the search")
                print("  -l, --listproducts    List all available products")
                sys.exit()
            elif opt in ("-s", "--search"):
                search_query = arg
            elif opt in ("-p", "--product"):
                products = get_products()
                product_name = arg
                if product_name not in products:
                    print("Product '{}' not found in the list of available products.".format(product_name))
                    print("Run: skb -l or  skb --listproducts")
                    sys.exit(1)
            elif opt in ("-l", "--listproducts"):
                print("Products from the SUSE Knowledgebase: ")
                products = get_products()
                for p in products:
                    print(p)
                sys.exit()
        tids = search_kb(product_name, search_query)
        tid = select_tid(tids, product_name, search_query)



