import json
import logging
from typing import Any, Dict, List

from utils.access import DriveManager


log = logging.getLogger(__name__)


def load_json(drive_manager: DriveManager, file_path: str) -> Dict[str, Any]:
    content = drive_manager.read_or_none(file_path)
    if not content:
        return {}

    try:
        return json.loads(content)
    except json.JSONDecodeError as e:
        log.warning(f"JSON parsing failed: {e}")
        return {}
    except Exception as e:
        log.warning(f"JSON parsing failed: {e}")
        return {}


def write_jsonl_or_false(
    drive_manager: DriveManager, file_path: str, items: List[Dict[str, Any]]
) -> bool:
    return drive_manager.write_or_false(file_path, json.dumps(items))


def write_piped_or_false(
    drive_manager: DriveManager, file_path: str, items: List[Dict[str, Any]]
) -> bool:
    piped = "\n".join(
        "|".join(str(v).replace("\n", " ") for v in item.values()) for item in items
    )
    return drive_manager.write_or_false(file_path, piped)
