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

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:
        user_messages = [
            next(msg['content'] for msg in item['messages'] if msg['role'] == 'user')
            for item in dataset
        ]
        
        vectorizer = TfidfVectorizer().fit(user_messages + [prompt])
        user_vectors = vectorizer.transform(user_messages)
        prompt_vector = vectorizer.transform([prompt])
        
        similarities = cosine_similarity(prompt_vector, user_vectors)[0]
        top_indices = np.argsort(similarities)[-num_examples:][::-1]
    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=512,
                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 process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity):
    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 p/python {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:
            if len(data.get("results", [])) == 0:
                tqdm.write(input_file + " has no vulnerabilities")
                result = False
            else:
                tqdm.write("Vulnerability found in " + input_file + "...")
                cwe = data["results"][0]["extra"]["metadata"]["cwe"][0]
                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."""
                
                few_shot_messages = fetch_dataset_examples(prompt, n_shot, use_similarity)
                response = get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name)
                
                if "```python" in response:
                    idx = response.find("```python")
                    shift = len("```python")
                    fixed_code = response[idx + shift :]
                else:
                    fixed_code = response
                
                stop_words = ["```", "assistant"]

                for w in stop_words:
                    if w in fixed_code:
                        fixed_code = fixed_code[:fixed_code.find(w)]
                if len(fixed_code) < 400:
                    result = False
                if has_all_comments(fixed_code):
                    result = False
                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 p/python {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["errors"]) == 0 and len(data["results"]) == 0:
                    tqdm.write("Passing response for " + input_file + " at 1 ...")
                    result = True
                    fixed_files.append(file_name)
                else:
                    result = False
        else:
            tqdm.write(f"Semgrep reported errors for {input_file}")
            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):
    return process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity)

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")
    args = parser.parse_args()

    model_name = args.model
    use_cache = args.cache
    n_shot = args.n_shot
    use_similarity = args.use_similarity
    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")
    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)

    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: {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("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()