"""JSON extraction and parsing utilities."""

import json
import re
from typing import Any

from loguru import logger


def extract_json(text: str) -> dict[str, Any]:
    """
    Extract JSON from text, handling unescaped control characters in strings.

    Args:
        text: Text containing JSON data

    Returns:
        Parsed JSON as dictionary, or empty dict if parsing fails
    """
    try:
        # First, try to parse the entire text as JSON
        text = text.strip()
        if not text:
            return {}
        return json.loads(text)
    except json.JSONDecodeError:
        try:
            # Extract the JSON object from the text
            json_start = text.index("{")
            json_end = text.rfind("}")
            json_str = text[json_start : json_end + 1]

            # Function to escape control characters in string values
            def escape_string(match: re.Match[str]) -> str:
                s = match.group(0)
                # Remove the enclosing quotes
                s = s[1:-1]
                # Escape backslashes and double quotes
                s = s.replace("\\", "\\\\").replace('"', '\\"')
                # Escape control characters
                s = s.replace("\b", "\\b").replace("\f", "\\f")
                s = s.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
                # Return the escaped string with quotes
                return f'"{s}"'

            # Regex pattern to find string values in the JSON
            string_pattern = r'(?P<quote>")(?P<string>.*?)(?P=quote)'
            # Use regex to escape control characters in all string values
            escaped_json_str = re.sub(string_pattern, escape_string, json_str, flags=re.DOTALL)

            # Now, try to parse the escaped JSON string
            return json.loads(escaped_json_str)
        except (ValueError, json.JSONDecodeError) as e:
            logger.error(f"Failed to extract JSON from text: {e}")
            logger.debug(f"Problematic text:\n{text}")
            return {}
