import json
from typing import List, Optional
from analogai.deepthink.presentation.parsers.parsed_sentence import ParsedSentence
from analogai.deepthink.presentation.parsers.parsed_sentence_extractor import parse_sentences
from analogai.deepthink.presentation.parsers.utils.condition_transformer import transform_condition_to_causal


def parse_json(json_str: str) -> List[ParsedSentence]:
    try:
        data = json.loads(json_str.strip())
    except json.JSONDecodeError:
        return []
    
    sentences_data = _get_sentences_data(data)
    
    result = []
    for sentence_data in sentences_data:
        transformed = transform_condition_to_causal(sentence_data)
        sentences = parse_sentences({"sentences": [transformed]})
        result.extend(sentences)
    
    return result


def _get_sentences_data(data: dict) -> List[dict]:
    if "sentences" in data:
        items = data["sentences"]
        return items if items else []
    if "intent" in data or "intent_type" in data:
        return [data]
    return []


def is_json_format(text: str) -> bool:
    if not text or not text.strip():
        return False
    stripped = text.strip()
    return (stripped.startswith("{") and stripped.endswith("}")) or (
        stripped.startswith("[") and stripped.endswith("]")
    )
