#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
resources/resolvers/torch_search.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Resolver per Torch Search Engine (motore di ricerca .onion).

Onion: http://torchdeedp3i2jigzjdmfpn5ttjhthh5wbmda2rr3jvqjg5p77c54dqd.onion

Espone:
    show_search()   ← mode=resolver, title2=torch_search
"""

import re as _re
import sys
import os

_ADDON_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if _ADDON_ROOT not in sys.path:
    sys.path.insert(0, _ADDON_ROOT)

import variables as var
import functions as func

ONION_URL = 'http://torchdeedp3i2jigzjdmfpn5ttjhthh5wbmda2rr3jvqjg5p77c54dqd.onion'


# ──────────────────────────────────────────────────────────────────────
# PARSER
# ──────────────────────────────────────────────────────────────────────

def _parse_results(html: str, base: str) -> list:
    """
    Estrae risultati dalla pagina di ricerca Torch.
    Struttura: lista di link <a href="...">Titolo</a> con descrizione.
    """
    from urllib.parse import urljoin

    results = []
    seen    = set()

    # Cerca tutti i link risultato (esclude link navigazione interni)
    PATTERN = r'<a\s+href="(https?://[^"]+)"[^>]*>([^<]{5,})</a>'
    for url, raw_title in _re.findall(PATTERN, html, _re.IGNORECASE):
        url   = url.strip()
        title = raw_title.strip()
        if url in seen or not title:
            continue
        # Salta link interni di Torch
        if ONION_URL in url or 'torchdeed' in url:
            continue
        seen.add(url)

        # Tipo: .onion o clearnet
        ltype = 'onion' if '.onion' in url else 'http'
        results.append({
            'title': f'[COLOR deepskyblue]{title[:60]}[/COLOR]',
            'url'  : url,
            'type' : ltype,
            'thumb': '',
        })

    return results[:50]


# ──────────────────────────────────────────────────────────────────────
# PUBBLICO
# ──────────────────────────────────────────────────────────────────────

def show_search() -> None:
    """Ricerca su Torch Search tramite Tor."""
    import xbmc as _xbmc
    from urllib.parse import quote_plus
    from onion_xml_builder import build_listitem

    kb = _xbmc.Keyboard('', 'Cerca su Torch (Tor)', False)
    kb.doModal()
    if not kb.isConfirmed():
        return
    query = kb.getText().strip()
    if not query:
        return

    var.notify_dialog('Torch Search', f'Cerca: {query}…', icon=var.addon_icon)
    q   = quote_plus(query)
    url = f'{ONION_URL}/search?query={q}&action=search'

    func.log(f'[torch] ricerca: {url}')
    html = func.get_onion(url, timeout=30)

    if not html:
        func.ok_dialog(
            'Impossibile raggiungere Torch.\n'
            'Verifica che Tor sia attivo su 127.0.0.1:9050'
        )
        return

    items = _parse_results(html, ONION_URL)
    if not items:
        func.ok_dialog(f'Nessun risultato per: "{query}"')
        return

    for entry in items:
        build_listitem(entry)
