import os
import torch
import json
from sentence_transformers import SentenceTransformer

device = "cuda:0"
model = SentenceTransformer("./models/law_bert", device=device)


def get_top_k_similar_items_torch(query_embedding, data, k=5):

    query_tensor = torch.tensor(query_embedding).float()
    data_tensor = torch.stack(
        [torch.tensor(item["embedding"]).float() for item in data]
    )

    query_norm = query_tensor / query_tensor.norm(dim=0)
    data_norm = data_tensor / data_tensor.norm(dim=1, keepdim=True)

    similarities = torch.matmul(data_norm, query_norm)

    top_k_scores, top_k_indices = torch.topk(similarities, k=k)

    return [
        {
            "article_number": data[i]["article_number"],
            "article_title": data[i]["article_title"],
            "text": data[i]["text"],
            "score": float(top_k_scores[j]),
        }
        for j, i in enumerate(top_k_indices)
    ]


data_path = "./data/new/"
children = os.listdir(data_path)

sentences = []
for child in children:
    with open(data_path + child, "r", encoding="utf-8") as read:
        for line in read:
            objz = json.loads(line)
            objz["embedding"] = model.encode(
                objz["article_title"] + "\n" + objz["text"]
            ).flatten()
            sentences.append(objz)

queries = [
    "NLĐ bị sa thải có được trả lương hay không?",
    "Người sử dụng lao động được sa thải người lao động nữ đang mang thai không?",
    "Quy định về điều chuyển nhân sự được quy định như thế nào?",
    "Người lao động được thuê làm giám đốc doanh nghiệp Nhà nước được hưởng các chế độ về tiền lương, thưởng như thế nào?",
    "Làm việc 8h một ngày thì được nghỉ giữa giờ ít nhất bao nhiêu phút?",
    "Người sử dụng lao động đào tạo nghề nghiệp và phát triển kỹ năng nghề cho người lao động như thế nào?",
    "Nguyên tắc cho thuê lại lao động là gì?",
    "Thời hạn của thỏa ước lao động tập thể như thế nào?",
    "Hợp đồng lao động được giao kết theo hình thức nào?",
    "Nội dung về đào tạo lao động có bắt buộc phải ghi vào hợp đồng lao động?",
]

for query in queries:
    top_matches = get_top_k_similar_items_torch(
        model.encode(query).flatten(), sentences, k=10
    )
    # print(top_matches)
    print(query)
    for item in top_matches:
        print(f"{item['article_number']} → {item['text']}")
    print()
