import requests
import sys
import xml.etree.ElementTree as ET
import re

BASE_FEED_URL = "https://feeds.feedburner.com/hlgamingofficial/{}"

def fetch_articles(user_api, count):
    """
    Fetches the latest articles with full details including images.
    """
    try:
        feed_url = BASE_FEED_URL.format(user_api)
        response = requests.get(feed_url)

        if response.status_code != 200:
            print("❌ Failed to fetch feed! Check your API key.")
            return

        root = ET.fromstring(response.content)
        items = root.findall(".//item")[:int(count)]

        if not items:
            print("⚠️ No articles found.")
            return

        print("📰 Latest Articles:")
        for item in items:
            print_article_details(item)

    except Exception as e:
        print(f"❌ Error: {e}")

def search_articles(user_api, search_term):
    """
    Searches for articles by keyword (in title, content, and categories).
    """
    try:
        feed_url = BASE_FEED_URL.format(user_api)
        response = requests.get(feed_url)

        if response.status_code != 200:
            print("❌ Failed to fetch feed! Check your API key.")
            return

        root = ET.fromstring(response.content)
        items = root.findall(".//item")

        results = []
        for item in items:
            title = item.find("title").text
            link = item.find("link").text
            description = item.find("description").text if item.find("description") is not None else ""
            categories = [category.text.lower() for category in item.findall("category")]

            if (search_term.lower() in title.lower() or 
                search_term.lower() in description.lower() or 
                any(search_term.lower() in cat for cat in categories)):
                results.append(item)

        if not results:
            print(f"⚠️ No articles found for '{search_term}'.")
            return

        print(f"🔍 Search Results for '{search_term}':")
        for item in results:
            print_article_details(item)

    except Exception as e:
        print(f"❌ Error: {e}")

def fetch_article_details(user_api, article_id):
    """
    Fetches full details of a specific article by ID.
    """
    try:
        feed_url = BASE_FEED_URL.format(user_api)
        response = requests.get(feed_url)

        if response.status_code != 200:
            print("❌ Failed to fetch feed! Check your API key.")
            return

        root = ET.fromstring(response.content)
        items = root.findall(".//item")

        for item in items:
            link = item.find("link").text
            if article_id.lower() in link.lower():  # Matching ID with link
                print_article_details(item)
                return

        print(f"⚠️ No article found with ID '{article_id}'.")

    except Exception as e:
        print(f"❌ Error: {e}")

def fetch_article_by_url(user_api, article_url):
    """
    Fetches full details of a specific article using its URL.
    """
    try:
        feed_url = BASE_FEED_URL.format(user_api)
        response = requests.get(feed_url)

        if response.status_code != 200:
            print("❌ Failed to fetch feed! Check your API key.")
            return

        root = ET.fromstring(response.content)
        items = root.findall(".//item")

        for item in items:
            link = item.find("link").text
            if link.strip() == article_url.strip():  # Exact URL match
                print_article_details(item)
                return

        print(f"⚠️ No article found for URL '{article_url}'.")

    except Exception as e:
        print(f"❌ Error: {e}")

def extract_images(description):
    """
    Extracts all image URLs from the <description> field.
    """
    if description:
        return re.findall(r'<img.*?src="(.*?)"', description)
    return []

def print_article_details(item):
    """
    Prints full details of an article including images.
    """
    title = item.find("title").text
    link = item.find("link").text
    description = item.find("description").text if item.find("description") is not None else "No content available."
    pub_date = item.find("pubDate").text if item.find("pubDate") is not None else "Unknown date"
    updated_date = item.find("{http://www.w3.org/2005/Atom}updated").text if item.find("{http://www.w3.org/2005/Atom}updated") is not None else "No update info"
    categories = [category.text for category in item.findall("category")]
    images = extract_images(description)

    print(f"\n🔹 **{title}**")
    print(f"🔗 {link}")
    print(f"📅 Published: {pub_date}")
    print(f"🆕 Updated: {updated_date}")
    print(f"🏷 Categories: {', '.join(categories)}")
    print(f"📝 Full Content: {description[:300]}...")  # Showing first 300 chars
    print(f"🖼 Images: {', '.join(images) if images else 'No images found'}")
    print("-" * 80)

def main():
    """
    Entry point for the hl-gaming-api command.
    """
    if len(sys.argv) < 4:
        print("❌ Usage:")
        print("   hl-gaming-api fetch {user_api} {count}")
        print("   hl-gaming-api search {user_api} {search_term}")
        print("   hl-gaming-api details {user_api} {article_id}")
        print("   hl-gaming-api url {user_api} {article_url}")
        return

    command = sys.argv[1]
    user_api = sys.argv[2]

    if command == "fetch":
        count = sys.argv[3]
        fetch_articles(user_api, count)
    elif command == "search":
        search_term = sys.argv[3]
        search_articles(user_api, search_term)
    elif command == "details":
        article_id = sys.argv[3]
        fetch_article_details(user_api, article_id)
    elif command == "url":
        article_url = sys.argv[3]
        fetch_article_by_url(user_api, article_url)
    else:
        print("❌ Unknown command! Use 'fetch', 'search', 'details', or 'url'.")
