import json
import os
import random
import pickle
import time
import datetime
import subprocess
import argparse
import re
import multiprocessing
import numpy as np
from openai import OpenAI
from openai import OpenAIError
from tqdm import tqdm
from functools import partial
from datasets import load_dataset
from sentence_transformers import SentenceTransformer, CrossEncoder
from sklearn.metrics.pairwise import cosine_similarity

# client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")
client = OpenAI()

def load_cache(use_cache):
    if use_cache and os.path.exists('cache.pkl'):
        with open('cache.pkl', 'rb') as f:
            return pickle.load(f)
    return {}

def save_cache(cache, use_cache):
    if use_cache:
        with open('cache.pkl', 'wb') as f:
            pickle.dump(cache, f)

def has_all_comments(text):
    lines=text.split('\n')
    for line in lines:
        if line != "" and not line.startswith("#"):
            return False
    return True

def fetch_dataset_examples(prompt, num_examples=0, use_similarity=False):
    dataset = load_dataset("patched-codes/synth-vuln-fixes", split="train")
    
    if use_similarity:
        # Load a lightweight model for initial retrieval
        retrieval_model = SentenceTransformer('all-MiniLM-L6-v2')
        
        # Load the cross-encoder model for reranking
        rerank_model = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
        
        # Extract user messages
        user_messages = [
            next(msg['content'] for msg in item['messages'] if msg['role'] == 'user')
            for item in dataset
        ]
        
        # Encode the prompt and user messages for initial retrieval
        prompt_embedding = retrieval_model.encode(prompt, convert_to_tensor=False)
        corpus_embeddings = retrieval_model.encode(user_messages, convert_to_tensor=False, show_progress_bar=True)
        
        # Perform initial retrieval
        similarities = cosine_similarity([prompt_embedding], corpus_embeddings)[0]
        top_k = min(100, len(dataset))
        top_indices = similarities.argsort()[-top_k:][::-1]
        
        # Prepare pairs for reranking
        rerank_pairs = [[prompt, user_messages[idx]] for idx in top_indices]
        
        # Rerank using the cross-encoder model
        rerank_scores = rerank_model.predict(rerank_pairs)
        
        # Sort by reranked score and select top examples
        reranked_indices = [top_indices[i] for i in np.argsort(rerank_scores)[::-1][:num_examples]]
        top_indices = reranked_indices
    else:
        top_indices = np.random.choice(len(dataset), num_examples, replace=False)
    
    few_shot_messages = []
    for index in top_indices:
        py_index = int(index)
        messages = dataset[py_index]["messages"]
        
        dialogue = [msg for msg in messages if msg['role'] != 'system']
        few_shot_messages.extend(dialogue)
    
    return few_shot_messages

def sanitize_filename(name):
    # Replace ':' with '_', and any other non-alphanumeric characters (except '-' and '_') with '*'
    sanitized = re.sub(r':', '_', name)
    sanitized = re.sub(r'[^a-zA-Z0-9\-_]', '*', sanitized)
    return sanitized

def get_semgrep_version():
    try:
        result = subprocess.run(["semgrep", "--version"], capture_output=True, text=True)
        version = result.stdout.strip().split()[-1]
        return version
    except Exception:
        return "unknown"

def get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name):
    system_message = (
        "You are an AI assistant specialized in fixing code vulnerabilities. "
        "Your task is to provide corrected code that addresses the reported security issue. "
        "Always maintain the original functionality while improving security. "
        "Be precise and make only necessary changes. "
        "Maintain the original code style and formatting unless it directly relates to the vulnerability. "
        "Pay attention to data flow between sources and sinks when provided."
    )

    messages = [
        {"role": "system", "content": system_message},
    ]
    
    messages.extend(few_shot_messages)
    messages.append({"role": "user", "content": prompt})

    max_retries = 3

    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model=model_name,
                messages=messages,
                max_tokens=4096,
                temperature=0.2,
                top_p=0.95
            )
            return response.choices[0].message.content
        except OpenAIError as e:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
            else:
                raise Exception(f"API call failed after {max_retries} attempts: {str(e)}")
            
def clean_code_snippet(response):
    # Remove opening delimiter
    if response.startswith("```python"):
        response = response[len("```python"):]
    elif response.startswith("```"):
        response = response[len("```"):]
    
    # Remove closing delimiter
    if response.endswith("```"):
        response = response[:-len("```")]
    
    # Trim any remaining whitespace
    return response.strip()

def process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode):
    file_name = test_case["file_name"]
    input_file = os.path.join("staticeval", file_name)
    
    if use_cache and input_file in cache:
        tqdm.write(f"Skipping {input_file} (cached)")
        return cache[input_file]

    file_text = test_case["source"]
    output_file = input_file + "_fixed.py"
    tmp_file = input_file + ".output.json"

    try:
        os.makedirs(os.path.dirname(input_file), exist_ok=True)

        with open(input_file, "w") as file_object:
            file_object.write(file_text)

        if os.path.exists(tmp_file):
            os.remove(tmp_file)
            
        tqdm.write("Scanning file " + input_file + "...")
        scan_command_input = f"semgrep --config auto {input_file} --output {tmp_file} --json > /dev/null 2>&1"
        os.system(scan_command_input)
        
        if not os.path.exists(tmp_file):
            tqdm.write(f"Semgrep failed to create output file for {input_file}")
            return False

        with open(tmp_file, 'r') as jf:
            data = json.load(jf)

        if len(data.get("errors", [])) > 0:
            tqdm.write(f"Error processing {input_file} ...")
            return False
            
        if len(data.get("results", [])) == 0:
            tqdm.write(input_file + " has no vulnerabilities")
            result = False
        else:
            tqdm.write("Vulnerability found in " + input_file + "...")
            if oracle_mode:
                result = True
                fixed_files.append(file_name)
            else:
                cwe = test_case['cwe']
                lines = data["results"][0]["extra"]["lines"]
                message = data["results"][0]["extra"]["message"]
                
                prompt = f"""Vulnerability Report:
    - Type: {cwe}
    - Location: {lines}
    - Description: {message}

    Original Code:
    ```
    {file_text}
    ```

    Task: Fix the vulnerability in the code above. Provide only the complete fixed code without explanations or comments. Make minimal changes necessary to address the security issue while preserving the original functionality."""
                # print(prompt)
                few_shot_messages = fetch_dataset_examples(prompt, n_shot, use_similarity)
                response = get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name)
                # print(response)
                
                fixed_code = clean_code_snippet(response)

                if len(fixed_code) < 512 or has_all_comments(fixed_code):
                    result = False
                else: 
                    # print("Here2\n" + fixed_code)
                    if os.path.exists(output_file):
                        os.remove(output_file)
                    with open(output_file, 'w') as wf:
                        wf.write(fixed_code)
                    if os.path.exists(tmp_file):
                        os.remove(tmp_file)
                    scan_command_output = f"semgrep --config auto {output_file} --output {tmp_file} --json > /dev/null 2>&1"
                    os.system(scan_command_output)
                    with open(tmp_file, 'r') as jf:
                        data = json.load(jf)
                    if len(data["results"]) == 0:
                        tqdm.write("Passing response for " + input_file + " at 1 ...")
                        result = True
                        fixed_files.append(file_name)
                    else:
                        result = False

        if os.path.exists(tmp_file):
            os.remove(tmp_file)
        if use_cache:
            cache[input_file] = result

        return result
    except Exception as e:
        tqdm.write(f"Error processing {input_file}: {str(e)}")
        return False

def process_test_case(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode):
    return process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode)

def main():
    parser = argparse.ArgumentParser(description="Run Static Analysis Evaluation")
    parser.add_argument("--model", type=str, default="gpt-4o-mini", help="OpenAI model to use")
    parser.add_argument("--cache", action="store_true", help="Enable caching of results")
    parser.add_argument("--n_shot", type=int, default=0, help="Number of examples to use for few-shot learning")
    parser.add_argument("--use_similarity", action="store_true", help="Use similarity for fetching dataset examples")
    parser.add_argument("--oracle", action="store_true", help="Run in oracle mode (assume all vulnerabilities are fixed)")
    args = parser.parse_args()

    model_name = "oracle" if args.oracle else args.model
    use_cache = args.cache
    n_shot = args.n_shot
    use_similarity = args.use_similarity
    oracle_mode = args.oracle
    sanitized_model_name = f"{sanitize_filename(model_name)}-{n_shot}-shot{'-sim' if use_similarity else ''}"

    dataset = load_dataset("patched-codes/static-analysis-eval", split="train", download_mode='force_redownload')
    data = [{"file_name": item["file_name"], "source": item["source"], "cwe": item["cwe"]} for item in dataset]

    cache = load_cache(use_cache)
    total_tests = len(data)

    semgrep_version = get_semgrep_version()
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file_name = f"{sanitized_model_name}_semgrep_{semgrep_version}_{timestamp}.log"

    manager = multiprocessing.Manager()
    fixed_files = manager.list()

    process_func = partial(process_test_case, cache=cache, fixed_files=fixed_files, model_name=model_name,
                           use_cache=use_cache, n_shot=n_shot, use_similarity=use_similarity, oracle_mode=oracle_mode)

    with multiprocessing.Pool(processes=4) as pool:
        results = list(tqdm(pool.imap(process_func, data), total=total_tests))

    passing_tests = sum(results)
    score = passing_tests / total_tests * 100

    if use_cache:
        save_cache(cache, use_cache)

    with open(log_file_name, 'w') as log_file:
        log_file.write(f"Evaluation Run Log\n")
        log_file.write(f"==================\n\n")
        log_file.write(f"Date and Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        log_file.write(f"Model: {'' if oracle_mode else model_name}\n")
        log_file.write(f"Semgrep Version: {semgrep_version}\n")
        log_file.write(f"Caching: {'Enabled' if use_cache else 'Disabled'}\n\n")
        log_file.write(f"Total Tests: {total_tests}\n")
        log_file.write(f"Passing Tests: {passing_tests}\n")
        log_file.write(f"Score: {score:.2f}%\n\n")
        log_file.write(f"Number of few-shot examples: {n_shot}\n")
        log_file.write(f"Use similarity for examples: {'Yes' if use_similarity else 'No'}\n")
        log_file.write(f"Oracle mode: {'Yes' if oracle_mode else 'No'}\n")
        log_file.write("Fixed Files:\n")
        for file in fixed_files:
            log_file.write(f"- {file}\n")

    print(f"Results for StaticAnalysisEval: {score:.2f}%")
    print(f"Log file created: {log_file_name}")

if __name__ == '__main__':
    main()