from pathlib import Path
import sys
import traceback


ROOT_DIR = Path(__file__).resolve().parents[1]
CONN_DIR = ROOT_DIR / "conn"
if str(CONN_DIR) not in sys.path:
    sys.path.insert(0, str(CONN_DIR))

import mysql5


def _legacy_start_guessing_manual(ticket):
    try:
        from sklearn.feature_extraction.text import TfidfVectorizer
        from sklearn.metrics.pairwise import cosine_similarity
    except Exception:
        traceback.print_exc()
        return []

    competence_origin, product_origin, problem_origin, area_origin, subarea_origin = mysql5.getCompetenceOrProdotto(ticket)
    w_list = mysql5.getProblemaBYCompetenzaOrProgramma_manul(competence_origin, product_origin, area_origin, subarea_origin)

    if len(w_list) == 0:
        return []

    phrases = [item[0] for item in w_list]
    vectorizer = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), lowercase=True)
    tfidf_matrix = vectorizer.fit_transform([problem_origin] + phrases)
    similarity_matrix = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:])

    # Keep the real top five. The old code used [-6:-1], which skipped the best result.
    best_matches_indices = similarity_matrix.argsort()[0][-5:][::-1]

    final_list = []
    for i, index in enumerate(best_matches_indices, start=1):
        complete_ticket = mysql5.getTicketByProblema(str(phrases[index]))
        solution = str(complete_ticket[1])
        if len(solution) > 400:
            solution = solution[:400] + "..."

        final_list.append(
            f"\n\n----- {i}. Metodo legacy -----\n"
            f"[ /Ticket_dettaglio_{complete_ticket[0]} ]\n"
            f"https://tsnew.sanmarcoweb.com/it/ticket/index/index/operation/view/id/{complete_ticket[0]}\n"
            f"SOLUZIONE: {solution}\n"
        )
    return final_list


def start_guessing_manual(ticket, user_id=None, filters=None, limit=None, offset=0):
    try:
        import ai_retriever

        kwargs = {"user_id": user_id, "filters": filters, "offset": offset}
        if limit is not None:
            kwargs["limit"] = limit
        return ai_retriever.start_guessing_manual(ticket, **kwargs)
    except Exception:
        traceback.print_exc()
        if filters:
            return []
        return _legacy_start_guessing_manual(ticket)
