import copy
import json
import random
import sys
from typing import Dict, Any
import re

placeholder_values = {
    "contact_name": "Alice Johnson",
    "opportunity_name": "Enterprise Expansion",
    "first_name": "Bob",
    "phone": "123-456-7890",
    "title": "New Contract Agreement",
    "full_name": "Charlie Smith",
    "email": "charlie.smith@example.com",
    "opp_name": "Growth Initiative",
    "amount": "50000"
}


def replace_placeholders(data: Any, placeholders: Dict[str, str]) -> Any:
    """
    Recursively traverse the data and replace placeholders in strings.

    Args:
        data: The data structure (dict, list, or str).
        placeholders: A dictionary mapping placeholder names to their replacements.

    Returns:
        The data structure with placeholders replaced.
    """
    if isinstance(data, dict):
        return {key: replace_placeholders(value, placeholders) for key, value in data.items()}
    elif isinstance(data, list):
        return [replace_placeholders(element, placeholders) for element in data]
    elif isinstance(data, str):
        return replace_in_string(data, placeholders)
    else:
        return data


def replace_in_string(s: str, placeholders: Dict[str, str]) -> str:
    """
    Replace all placeholders in the string with their corresponding values.

    Args:
        s: The input string containing placeholders.
        placeholders: A dictionary mapping placeholder names to their replacements.

    Returns:
        The string with placeholders replaced.
    """
    pattern = re.compile(r'\{\{(\w+?)\}\}')

    def replacer(match):
        key = match.group(1)
        return placeholders.get(key, match.group(0))  # If key not found, keep original

    return pattern.sub(replacer, s)


def load_json_file(file_path: str) -> Any:
    """
    Load JSON data from a file.

    Args:
        file_path (str): Path to the JSON file.

    Returns:
        Any: Parsed JSON data.
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"Error: Failed to parse JSON from '{file_path}'. {e}")
        sys.exit(1)


def save_json_file(data: Any, file_path: str) -> None:
    """
    Save JSON data to a file.

    Args:
        data (Any): Data to save.
        file_path (str): Path to the output JSON file.
    """
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2)
        print(f"Filled tasks have been saved to '{file_path}'.")
    except Exception as e:
        print(f"Error: Could not write to '{file_path}'. {e}")
        sys.exit(1)


def main(tasks_file: str, output_file: str, placeholders) -> None:
    """
    Main function to load tasks and placeholders, perform replacement, and save the result.

    Args:
        tasks_file (str): Path to the tasks JSON file.
        placeholders_file (str): Path to the placeholders JSON file.
        output_file (str): Path to save the filled tasks JSON.
    """
    tasks = load_json_file(tasks_file)
    # ww = json.dumps(tasks)
    #
    # # Find all matches between {{ and }}
    # matches = re.findall(r'\{\{(.*?)\}\}', ww)
    #
    # print(list(set(matches)))
    # placeholders = load_json_file(placeholders)

    filled_tasks = replace_placeholders(tasks, placeholders)
    #
    return filled_tasks
    # save_json_file(filled_tasks, output_file)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Fill placeholders in tasks JSON with provided values.")
    parser.add_argument(
        "--tasks",
        type=str,
        default="./filtered_web_arena/error_templates.json",
        help="Path to the tasks JSON file (default: tasks.json)"
    )
    # parser.add_argument(
    #     "--placeholders",
    #     type=str,
    #     default="placeholders.json",
    #     help="Path to the placeholders JSON file (default: placeholders.json)"
    # )
    parser.add_argument(
        "--output",
        type=str,
        default="filled_tasks.json",
        help="Path to the output filled tasks JSON file (default: filled_tasks.json)"
    )

    args = parser.parse_args()
    existing_opportunity_name = ["E-commerce Platform", "HR Management System", "Blockchain Integration",
                                 "Customer Data Platform", "IoT Device Setup", "AI Integration", "ERP Deployment",
                                 "Data Analytics Implementation", "Cybersecurity Upgrade", "Cloud Migration"]
    existing_opp_name = ["Website Redesign", "Mobile App Development", "Cloud Migration", "Cybersecurity Upgrade",
                         "Data Analytics Implementation", "Video Streaming Platform",
                         "Remote Work Suite",
                         "Smart City Solutions",
                         "Customer Loyalty Program",
                         "Predictive Maintenance System"]
    new_opp_amount = ["13123", "123121", "32355", "43636", "234243", "14123", "123181", "32385", "43936", "231243"]

    new_contact_email = [
        "opal.sage@example.com",
        "thaddeus.cane@example.com",
        "fiona.ravenwood@example.com",
        "magnus.stone@example.com",
        "elara.nightingale@example.com",
        "lorelei.moonstone@example.com",
        "cassian.wylde@example.com",
        "selene.dusk@example.com",
        "dorian.ember@example.com",
        "astra.solace@example.com"
    ]

    new_contact_full_name = [
        "Opal Sage",
        "Thaddeus Cane",
        "Fiona Ravenwood",
        "Magnus Stone",
        "Elara Nightingale",
        "Lorelei Moonstone",
        "Cassian Wylde",
        "Selene Dusk",
        "Dorian Ember",
        "Astra Solace"
    ]
    existing_contact_name = ["Kelly Kapoor", "Phyllis Vance", "Meredith Palmer", "Creed Bratton", "Roy Anderson",
                             "Darryl Philbin",
                             "Erin Hannon",
                             "Andy Bernard",
                             "Jan Levinson",
                             "Holly Flax"
                             ]
    new_lead_first_name = [
        "Eldric", "Soraya", "Thalassa", "Peregrine", "Zephyr",
        "Calista", "Orion", "Lyric", "Ember", "Asher"
    ]
    new_lead_phone = [
        "555-0198", "555-0234", "555-0456", "555-0678", "555-0890",
        "555-1012", "555-1213", "555-1415", "555-1617", "555-1819"
    ]

    contract_title = [
        "Service Agreement",
        "Non-Disclosure Agreement",
        "Sales Contract",
        "Employment Contract",
        "Partnership Agreement",
        "Lease Agreement",
        "Consulting Agreement",
        "Confidentiality Agreement",
        "Supply Agreement",
        "Freelance Contract"
    ]

    contact_name_w_email = [
        "Michael Scott",
        "Pam Beesly",
        "Jim Halpert",
        "Dwight Schrute",
        "Angela Martin",
        'Oscar Martinez', 'Kevin Malone', 'Stanley Hudson', 'Ryan Howard', 'Toby Flenderson'
    ]
    data_range = {
        'new_opp_amount': new_opp_amount,
        'new_contact_email': new_contact_email,
        'new_contact_full_name': new_contact_full_name,
        "existing_contact_name": existing_contact_name,
        "new_lead_first_name": new_lead_first_name,
        "contact_name_w_email": contact_name_w_email,
        "new_lead_phone": new_lead_phone,
        "contract_title": contract_title,
        "existing_opportunity_name": existing_opportunity_name,
        "existing_opp_name": existing_opp_name,
    }
    all_data = []
    for i in range(0, 10):
        data_range_copy = copy.deepcopy(data_range)
        for key in data_range_copy.keys():
            data_range_copy[key] = data_range[key][i]
        filled_tasks = main(args.tasks, args.output, data_range_copy)
        all_data = all_data + filled_tasks
    sorted_tasks = sorted(all_data, key=lambda x: x["task_id"])
    save_json_file(sorted_tasks, "./policy_data/trust_data.json")