from typing import Dict
from datetime import datetime


def check_dates(d_date: Dict) -> str:
    """Check valid dates

    Parameters
    ----------
    d_date : Dict
        dictionary with dates from open insider

    Returns
    ----------
    error : str
        error message. If empty, no error.
    """
    possible_dates = [
        "All dates",
        "Custom",
        "Latest Day",
        "Last 3 days",
        "Last 1 week",
        "Last 2 weeks",
        "Last 1 month",
        "Last 2 months",
        "Last 3 months",
        "Last 6 months",
        "Last 1 year",
        "Last 2 years",
        "Last 4 years",
    ]

    error = ""

    if d_date["FilingDate"] not in possible_dates:
        error += (
            f"Invalid FilingDate '{d_date['FilingDate']}'. "
            f"Choose one of the following options: {', '.join(possible_dates)}.\n"
        )
    else:
        if d_date["FilingDate"] == "Custom":
            try:
                datetime.strptime(d_date["FilingDateFrom"], "%Y-%m-%d")
            except ValueError:
                error += f"Invalid FilingDateFrom '{d_date['FilingDateFrom']}' (format: dd/mm/yyyy).\n"
            try:
                datetime.strptime(d_date["FilingDateTo"], "%Y-%m-%d")
            except ValueError:
                error += f"Invalid FilingDateTo '{d_date['FilingDateTo']}' (format: dd/mm/yyyy).\n"

    if d_date["TradingDate"] not in possible_dates:
        error += (
            f"Invalid TradingDate '{d_date['TradingDate']}'. "
            f"Choose one of the following options: {', '.join(possible_dates)}.\n"
        )
    else:
        if d_date["TradingDate"] == "Custom":
            try:
                datetime.strptime(d_date["TradingDateFrom"], "%Y-%m-%d")
            except ValueError:
                error += f"Invalid TradingDateFrom '{d_date['TradingDateFrom']}' (format: dd/mm/yyyy).\n"

            try:
                datetime.strptime(d_date["TradingDateTo"], "%Y-%m-%d")
            except ValueError:
                error += f"Invalid TradingDateTo '{d_date['TradingDateTo']}' (format: dd/mm/yyyy).\n"

    return error