import json
from graph_search import *
import networkx as nx

def generate_time_based_narrative(graph, nodes):
    sorted_nodes = sort_nodes_by_timestamp(graph, nodes)
    narrative_parts = []
    
    for node in sorted_nodes:
        timestamp = graph.nodes[node].get('timestamp')
        description = graph.nodes[node].get('description')
        entity_type = graph.nodes[node].get('entity_type')
        
        neighbors = list(graph.neighbors(node))
        
        if not neighbors and entity_type == 'paper' and description:
            # Format for nodes without neighbors and entity type 'paper'
            narrative_parts.append(f"In {timestamp} --> {node} --> introduced a method that --> {description}.")
        elif neighbors:
            # Format for nodes with neighbors
            relations = [f"{node} --> {graph[node][neighbor]['relation']} --> {neighbor}" for neighbor in neighbors]
            narrative_parts.append(f"In {timestamp} --> " + " --> ".join(relations) + ".")
    
    return "\n".join(narrative_parts)

def create_cot_narrative_using_llm(graph, nodes,query):
    narrative = generate_time_based_narrative(graph, nodes)

    # Chain of Thought (CoT) LLM Prompt
    # prompt = f"""The following text provides a chronological summary of research advancements in a specific field:\n\n{narrative}\n\nPlease generate a logical and coherent narrative that highlights how each research work built on previous efforts, focusing on methods and solutions over time."""
    prompt = f"""
    You will now read a chronological summary of research advancements in a specific field,which is about {query}:\n\n{narrative}\n\n
    Please follow these steps to generate a logical and coherent narrative:

    1. **Identify key research milestones**: Extract the most significant works from the summary and list them chronologically.
    2. **Explain the methods and solutions**: For each research milestone, briefly describe the methods, techniques, or approaches that were introduced.
    3. **Show connections between works**: Explain how each research work built upon or responded to previous efforts. Highlight any improvements, adaptations, or breakthroughs.
    4. **Emphasize progression over time**: Focus on how the field evolved methodologically, emphasizing long-term trends or shifts in thinking.

    By following these steps, ensure that the final narrative clearly demonstrates the progression of research in a logical and connected way.
    """   
    messages = prompt
    cot_narrative = call_with_stream(messages)  # Replace with actual LLM call
    
    return cot_narrative,narrative

def generate_relatedwork(cot_narrative,topic,subtitle):
    # generate_relatedwork_prompt=f"""这是我们按照topic:{topic}搜索得到的具有时间逻辑的逻辑文本:\n\n\n{cot_narrative}\n\n\n,请按照如下的subtitle:{subtitle},挑选出最符合这个topic和subtitle的相关内容,并且生成符合这个topic和subtitle的论文的related work部分,并且请严格符合论文中related work的逻辑,然后给出related work部分,并给出在未来这个方向可能的发展方向和技术路线并以json的形式体现"""
    generate_relatedwork_prompt = f"""
    Based on the topic: {topic}, we have gathered a logically coherent narrative with a time-based progression as follows:\n\n{cot_narrative}\n\n\n

    Please follow the steps below to perform step-by-step reasoning and generate a high-quality "Related Work" section for a research paper, along with future directions for this topic:

    1. **Analyze the topic and time-based logic**: First, thoroughly analyze the given time-based narrative `{cot_narrative}` to identify the most relevant research work related to the topic: `{topic}` and subtitle: `{subtitle}`.

    2. **Select related work**: Based on the analysis, select the most representative studies, ensuring that they cover different time points or phases of technological development. Construct a coherent "Related Work" section, adhering to the standard logical structure typically found in academic papers.

    3. **Reason about future directions**: Based on the current state of research and technological progress, reasonably predict potential future directions and technical roadmaps. Please make these predictions by considering current challenges, technological bottlenecks, and cutting-edge developments. Provide a well-structured outlook on future research directions.

    The final output should include two parts:
    - A well-structured "Related Work" section for the paper.
    - A logical and forward-looking prediction of future research directions and technological advancements.

    Finally, present the future directions and technical roadmaps in JSON format.

    Example output format:\n"""
    example= """"
---

**Related Work**

The intersection of NLP and machine learning techniques has seen considerable advancements, particularly through the lens of in-context learning, hypernetworks, and knowledge distillation. This section delves into the foundational works and recent innovations that underpin our research.

*Hypernetworks*, initially conceptualized to dynamically generate weights for a main network based on the inputs [Ha, Dai, and Le, 2016], have opened novel avenues for model adaptability and task-specific tuning without comprehensive retraining. Hypernetworks' application in NLP, particularly for in-context learning, represents an emerging frontier. While still nascent, their potential to dynamically adapt language models for specific tasks or domains by generating context-aware weights promises a leap in model efficiency and specificity [Brock et al., 2017].

In the realm of *Knowledge Distillation* (KD), the technique has evolved from a method of model compression to a sophisticated tool for enhancing model performance and transfer learning in NLP [Hinton, Vinyals, and Dean, 2015]. KD's ability to transfer knowledge from larger, cumbersome models to smaller, more efficient ones has been pivotal in deploying advanced NLP models on resource-constrained environments. Recent works have extended KD by incorporating contextual information within the distillation process, yielding models that retain high levels of performance while being exposed to fewer examples [Sanh et al., 2019].

The synergy between hypernetworks and knowledge distillation within the context of in-context learning in NLP is yet to be fully explored. However, preliminary works suggest that hypernetworks could be employed to dynamically adjust the architecture of student models in a KD setup, potentially tailoring them better to the task at hand based on contextually generated cues. This could further augment the efficiency and efficacy of the distillation process, especially in scenarios requiring the rapid adaptation of models across diverse NLP tasks.

---

**Future Directions**

The integration of hypernetworks and knowledge distillation within in-context learning frameworks presents several promising research trajectories and technical roadmaps:

```json
{
  "Future_Directions": {
    "1. Dynamic Architectural Adjustments via Hypernetworks": {
      "Description": "Exploring the potential of hypernetworks to dynamically adjust the architecture of NLP models during the knowledge distillation process, based on the specifics of the task and contextual cues.",
      "Technical_Roadmap": [
        "Develop adaptive hypernetwork-driven models capable of real-time architectural adjustments.",
        "Investigate the impact of these adjustments on the knowledge distillation process and overall model performance."
      ]
    },
    "2. Context-Aware Knowledge Distillation": {
      "Description": "Incorporating context-aware strategies into the knowledge distillation process to enhance the transfer of task-specific insights from teacher to student models in NLP.",
      "Technical_Roadmap": [
        "Evaluate different context-embedding techniques for their efficacy in enriching the KD process.",
        "Pilot studies on the integration of contextual embeddings with KD for in-context learning applications."
      ]
    },
    "3. Comprehensive Benchmarks for Hypernetworks and KD in NLP": {
      "Description": "Establishing robust benchmarks to evaluate the effectiveness of hypernetwork and KD innovations within the NLP domain, particularly focusing on in-context learning tasks.",
      "Technical_Roadmap": [
        "Creation of benchmark datasets and evaluation protocols tailored to the specifics of hypernetworks and knowledge distillation.",
        "Longitudinal studies to assess the evolution and impact of these technologies on NLP."
      ]
    }
  }
}
```"""
    messages =  generate_relatedwork_prompt+example
    final_related_work = call_with_stream(messages)

    return final_related_work


if __name__ == '__main__':
    csv_path_floder=""
    json_path_floder=""
    
