from typing import List, Dict, Any, Optional
from datetime import datetime


def extract_latest_date_from_docs(retrieved_docs: List[Dict[str, Any]]) -> Optional[str]:
    if not retrieved_docs:
        return None

    valid_dates = []

    for doc in retrieved_docs:
        metadata = doc.get('metadata', {})
        extracted_date = metadata.get('extracted_date')

        if extracted_date and extracted_date != 'null' and extracted_date is not None:
            try:
                date_obj = datetime.strptime(extracted_date, "%Y-%m-%d")
                valid_dates.append((extracted_date, date_obj))
            except (ValueError, TypeError):
                continue

    if not valid_dates:
        return None

    latest_date = max(valid_dates, key=lambda x: x[1])
    return latest_date[0]


def format_qa_time_field(retrieved_docs: List[Dict[str, Any]]) -> Optional[str]:
    """
    Format the time field of QA pairs

    Args:
        retrieved_docs: List of retrieved documents

    Returns:
        Formatted time string or None
    """
    latest_date = extract_latest_date_from_docs(retrieved_docs)
    return latest_date
