import logging
from typing import List

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def summarize_context(context: str, max_length: int = 0) -> str:
    """
    Summarizes the given context to reduce its length while preserving key information.
    If max_length is set, truncate if it exceeds this length, adding ellipses.
    For now, this keeps only the first and last sentences.

    Args:
        context (str): The input context string.
        max_length (int): If specified, limit the context string to a maximum length.

    Returns:
        str: The summarized context.
    """
    try:
        sentences: List[str] = context.split('.')
        sentences = [s.strip() for s in sentences if s.strip()] # remove empty strings
        if not sentences:
            return ""

        if len(sentences) == 1:
            summary = sentences[0]
        else:
            summary = sentences[0] + '. ' + sentences[-1]

        if max_length > 0 and len(summary) > max_length:
            summary = summary[:max_length] + "..."

        return summary
    except Exception as e:
        logging.error(f"Error during context summarization: {e}")
        return context  # Return original context in case of error


if __name__ == '__main__':
    # Example usage
    context = "This is the first sentence. This is the second sentence. This is the third sentence. This is the last sentence."
    summarized_context = summarize_context(context)
    print(f"Original Context: {context}")
    print(f"Summarized Context: {summarized_context}")

    context = "This is a short sentence."
    summarized_context = summarize_context(context)
    print(f"Original Context: {context}")
    print(f"Summarized Context: {summarized_context}")

    context = ""
    summarized_context = summarize_context(context)
    print(f"Original Context: {context}")
    print(f"Summarized Context: {summarized_context}")

    context = "This is a very long sentence that exceeds the maximum length specified."
    summarized_context = summarize_context(context, 20)
    print(f"Original Context: {context}")
    print(f"Summarized Context: {summarized_context}")