import json
import os
import sys
import argparse
from datetime import datetime

# Configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
KB_FILE = os.path.join(BASE_DIR, "knowledge_base.json")

def load_kb():
    if not os.path.exists(KB_FILE):
        return []
    try:
        with open(KB_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading KB: {e}")
        return []

def save_kb(data):
    try:
        with open(KB_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
    except Exception as e:
        print(f"Error saving KB: {e}")
        sys.exit(1)

def register_source(url, description, category, tags):
    kb = load_kb()
    
    # Check for duplicates
    for entry in kb:
        if entry.get("url") == url:
            print(f"URL already registered: {url}")
            return

    new_entry = {
        "url": url,
        "description": description,
        "category": category,
        "tags": tags,
        "added_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    kb.append(new_entry)
    save_kb(kb)
    
    print("SUCCESS: Knowledge Source Registered")
    print(json.dumps(new_entry, indent=2, ensure_ascii=False))

def list_sources(filter_text=None):
    kb = load_kb()
    print(f"Total Sources: {len(kb)}")
    for entry in kb:
        if filter_text:
            search_content = (entry['url'] + entry['description'] + entry['category']).lower()
            if filter_text.lower() not in search_content:
                continue
        print(f"[{entry['category']}] {entry['description']} ({entry['url']})")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Register knowledge sources for iT Guys.")
    subparsers = parser.add_subparsers(dest="command", required=True)

    # Add command
    add_parser = subparsers.add_parser("add", help="Add a new source")
    add_parser.add_argument("--url", required=True, help="URL of the source")
    add_parser.add_argument("--description", required=True, help="Short description")
    add_parser.add_argument("--category", default="General", help="Category (Docs, Tool, Reference)")
    add_parser.add_argument("--tags", nargs="*", default=[], help="Tags provided as space-separated list")

    # List command
    list_parser = subparsers.add_parser("list", help="List sources")
    list_parser.add_argument("filter", nargs="?", help="Optional filter text")

    args = parser.parse_args()
    
    if args.command == "add":
        register_source(args.url, args.description, args.category, args.tags)
    elif args.command == "list":
        list_sources(args.filter)
