"""Built Simple Research - Jupyter Magic Commands"""
from IPython.core.magic import register_line_magic, register_cell_magic
from IPython.display import display, HTML, Markdown
import httpx
import json

def _search_pubmed(query, limit=5):
    r = httpx.post("https://pubmed.built-simple.ai/search", 
                   json={"query": query, "limit": limit})
    return r.json().get("results", [])

def _search_arxiv(query, limit=5):
    r = httpx.get(f"https://arxiv.built-simple.ai/api/search", 
                  params={"q": query, "limit": limit})
    return r.json().get("results", [])

def _search_wikipedia(query, limit=5):
    r = httpx.post("https://wikipedia.built-simple.ai/api/search", 
                   json={"query": query, "limit": limit})
    return r.json().get("results", [])

def _format_results(results, source):
    html = f"<h4>{source}</h4><ul>"
    for r in results:
        title = r.get("title", "Untitled")
        url = r.get("url") or r.get("link", "#")
        html += f'<li><a href="{url}" target="_blank">{title}</a></li>'
    return html + "</ul>"

@register_line_magic
def pubmed(query):
    """Search PubMed: %pubmed cancer treatment"""
    results = _search_pubmed(query)
    display(HTML(_format_results(results, "PubMed")))

@register_line_magic
def arxiv(query):
    """Search ArXiv: %arxiv transformer attention"""
    results = _search_arxiv(query)
    display(HTML(_format_results(results, "ArXiv")))

@register_line_magic
def wiki(query):
    """Search Wikipedia: %wiki machine learning"""
    results = _search_wikipedia(query)
    display(HTML(_format_results(results, "Wikipedia")))

@register_line_magic
def research(query):
    """Search all: %research neural networks"""
    pubmed_r = _search_pubmed(query, 3)
    arxiv_r = _search_arxiv(query, 3)
    wiki_r = _search_wikipedia(query, 3)
    
    html = f"<h3>Research: {query}</h3>"
    html += _format_results(pubmed_r, "PubMed")
    html += _format_results(arxiv_r, "ArXiv")
    html += _format_results(wiki_r, "Wikipedia")
    display(HTML(html))

def load_ipython_extension(ipython):
    pass  # Magics are registered automatically
