from typing import List, Tuple
import json
import os
import requests
from dotenv import load_dotenv
import re

ALPHABET = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
]
MODELS_API = {"deepseek-chat": "deepseek"}

LANGUAGE_CLASS_ORDER = ["R", "DCF", "CF", "CS"]
LANGUAGE_CLASSES = {
    "even-pairs": "R",
    "repeat-01": "R",
    "parity": "R",
    "cycle-navigation": "R",
    "modular-arithmetic-simple": "R",
    "dyck-2-3": "R",
    "first": "R",
    "majority": "DCF",
    "stack-manipulation": "DCF",
    "marked-reversal": "DCF",
    "unmarked-reversal": "CF",
    "marked-copy": "CS",
    "missing-duplicate-string": "CS",
    "odds-first": "CS",
    "binary-addition": "CS",
    "binary-multiplication": "CS",
    "compute-sqrt": "CS",
    "bucket-sort": "CS",
}


def last_binary_digit(s):
    try:
        for char in reversed(s):
            if char in ("0", "1"):
                return char
        return None  # or raise an error, or return a default value
    except Exception as e:
        print(f"Error: {e}")
        return None


def print_label_stats(data: List[Tuple[str, int]], name: str = ""):
    """Print statistics about label distribution in the data."""
    total = len(data)
    if total == 0:
        return

    labels = [label for _, label in data]
    num_label_0 = sum(1 for label in labels if label == 0)
    num_label_1 = sum(1 for label in labels if label == 1)

    print(f"\n{name} statistics:")
    print(f"Total examples: {total}")
    print(f"Label 0: {num_label_0} ({num_label_0/total*100:.1f}%)")
    print(f"Label 1: {num_label_1} ({num_label_1/total*100:.1f}%)")


def save_dict_to_json(data, filename):
    try:
        # Ensure the directory exists
        os.makedirs(os.path.dirname(filename), exist_ok=True)

        # Save the JSON file
        with open(filename, "w") as f:
            json.dump(data, f, indent=4)

        print(f"Successfully saved to {filename}")

    except Exception as e:
        print(f"Error saving data to {filename}: {e}")
