import re
import time


def parse_argos(string):
    """Parse timestamp from string

    For simplicity, assumes timestamps are as recent as the year 2000

    Parameters
    ----------
    string : str
        String containing timestamp substring with format YYYYmmdd_HHMMSS
        where
            YYYY = year
            mm = month
            dd = day
            HH = hour (24-hour format)
            MM = minute
            SS = second
        Example: 20200102_140203 -> 2:02:03 pm on Jan 2nd, 2020

    Returns
    -------
    ctime
        time.struct_time object of timestamp or None if not found
    """
    assert isinstance(string, str)

    search_str = r"([12][0-9]{3})([0-9]{2})([0-9]{2})_([0-9]{2})([0-9]{2})([0-9]{2})"
    matches = re.findall(search_str, string)
    assert len(matches) <= 1, f"found more than one timestamp: {string}"
    if matches:
        Y, m, d, H, M, S = map(int, matches[0])

        assert m in range(1, 13), f"invalid month: {m} in {string}"
        if m == 2:
            # Feb
            if Y % 4 == 0:
                # leap year
                assert d in range(1, 30), f"invalid day: {d} in {string}"
            else:
                assert d in range(1, 29), f"invalid day: {d} in {string}"
        elif m in (1, 3, 5, 7, 8, 10, 12):
            assert d in range(1, 32), f"invalid day: {d} in {string}"
        else:
            assert d in range(1, 31), f"invalid day: {d} in {string}"
        assert H in range(24), f"invalid hour: {H} in {string}"
        assert M in range(60), f"invalid minute: {M} in {string}"
        assert S in range(60), f"invalid second: {S} in {string}"
        # ctime = time.strptime(time_str[0], r"%Y%m%d_%H%M%S")
        ctime = time.struct_time((Y, m, d, H, M, S, 0, 0, 0))
    else:
        ctime = None
    return ctime