import json
import re
from pathlib import Path

import yaml


def yaml_load(file="data.yaml", append_filename=False):
    """
    Load YAML data from a file.
    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.
    Returns:
        dict: YAML data and file name.
    """
    with open(file, errors="ignore", encoding="utf-8") as f:
        s = f.read()  # string

        # Remove special characters
        if not s.isprintable():
            s = re.sub(
                r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+",
                "",
                s,
            )

        # Add YAML filename to dict and return
        return (
            {**yaml.safe_load(s), "yaml_file": str(file)}
            if append_filename
            else yaml.safe_load(s)
        )


def yaml_save(file="data.yaml", data=None):
    """
    Save YAML data to a file.
    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        data (dict, optional): Data to save in YAML format. Default is None.
    Returns:
        None: Data is saved to the specified file.
    """
    file = Path(file)
    if not file.parent.exists():
        # Create parent directories if they don't exist
        file.parent.mkdir(parents=True, exist_ok=True)

    with open(file, "w") as f:
        # Dump data to file in YAML format, converting Path objects to strings
        yaml.safe_dump(
            {k: str(v) if isinstance(v, Path) else v for k, v in data.items()},
            f,
            sort_keys=False,
            allow_unicode=True,
        )


def write_txt(txt, data, mode="w"):
    with open(txt, mode, encoding="utf8") as f:
        for line in data:
            f.write(line + "\n")


def read_txt(txt):
    with open(txt, "r", encoding="utf8") as f:
        data = [line.strip() for line in f]
    return data


def write_json(json_path, data, sort_keys=True):
    with open(json_path, "w", encoding="utf8") as f:
        json.dump(data, f, ensure_ascii=False, sort_keys=sort_keys)


def read_json(json_path):
    with open(json_path, "r", encoding="utf8") as f:
        data = json.load(f)
    return data



def load_ocr_output(txt_path):
    with open(txt_path) as f:
        lines = [line.replace("\n", "").replace("\r", "") for line in f.readlines()]
    words, boxes, labels = [], [], []
    for i, line in enumerate(lines):
        if len(line.split("\t")) == 6:
            x1, y1, x2, y2, text, label = line.split("\t")
        else:
            x1, y1, x2, y2, text = line.split("\t")
            label = None

        x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
        box = [x1, y1, x2, y2]
        if text != " ":
            words.append(text)
            boxes.append(box)
            labels.append(label)

    return {"boxes": boxes, "texts": words, 'labels': labels}
