import streamlit as st
import get_results
import pandas as pd
import pipelineoperation
import json
import insert_data

#st.image("/home/sankalp-user/Pictures/schematiselda.png")

st.write("<h4>Please visit the <a href='https://sankalpsrv.in/blog'>detailed blog post </a> and <a href = 'https://deepnote.com/workspace/mutaabik-bb27ba89-ef3a-49de-b973-2fca2f4c74b7/project/ICAT-Beta-90d69f02-b39a-4259-98fa-d4c4ad7d7557/notebook/Notebook%201-8b7b316e2a394f56ae2b43e06e1530f1'>Data Analytics Platform </a> for more and; See more by Schematise on <a href = 'https://linktr.ee/schematiselda'>  Linktree </a> <br> <a href='https://www.buymeacoffee.com/schematise' target='_blank'><img src='https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png' alt='Buy Me A Coffee' style='height: 60px;width: 217px;' ></a></a> </h4>", unsafe_allow_html=True) 

st.image("./ikanoon6_powered_transparent.png")

#st.write("<a href = 'https://huggingface.co/datasets/schematise/ICAT-version1/blob/main/Competition.pdf'> <b> SEE THE QUERY COMPETITION RULES HERE </b> </a>", unsafe_allow_html=True)



#st.image("./")

st.title("Get example contract clauses - ICAT Query Pipeline (BETA)")

searchquery = st.text_input("Search query for type of contracts e.g. 'arbitration', 'termination', 'trademark licensing'")

results = get_results.main(searchquery)


#st.dataframe(results)

df = pd.DataFrame(results)

dict_results = df.to_dict('records')

st.button("Generate/View results after text-classification")

# Serialize and write the dictionary to a file
with open("Dict_Results.txt", "w") as fn:
    json.dump(dict_results, fn)

if st.button:
    results_from_classifier = pipelineoperation.pipeline_operations(dict_results)
else:
    results_from_classifier = {}

with open ("ResultsAfterClassification.txt", "w") as fn:
    fn.write(str(results_from_classifier))

try:

    dict_from_classified_results = [{'Title': result['Title'],
                        'Matching clauses': result['matching_columns_after_classification'] + result['matching_indents_after_classification']
                        } for result in results_from_classifier]

    filtered_data_list = [item for item in dict_from_classified_results if item.get('Matching clauses')]

    df_to_display = pd.DataFrame(filtered_data_list)
    st.dataframe(df_to_display)

    insert_data.add_classified_results(results_from_classifier, searchquery)

except Exception as e:
    print(f"Error code: {e}")
    st.write("Error: Click on the generate button if you haven't already")