"""
You've sneaked into another supply closet - this time, it's across from
the prototype suit manufacturing lab. You need to sneak inside and fix
the issues with the suit, but there's a guard stationed outside the lab,
so this is as close as you can safely get.

As you search the closet for anything that might help, you discover that
you're not the first person to want to sneak in. Covering the walls,
someone has spent an hour starting every midnight for the past few months
secretly observing this guard post! They've been writing down the ID of
the one guard on duty that night - the Elves seem to have decided that
one guard was enough for the overnight shift - as well as when they fall
asleep or wake up while at their post (your puzzle input).

For example, consider the following records, which have already been organized into chronological order:

[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up

Timestamps are written using year-month-day hour:minute format. The guard
falling asleep or waking up is always the one whose shift most recently
started. Because all asleep/awake times are during the midnight hour
(00:00 - 00:59), only the minute portion (00 - 59) is relevant for
those events.

Visually, these records show that the guards are asleep at these times:

Date   ID   Minute
            000000000011111111112222222222333333333344444444445555555555
            012345678901234567890123456789012345678901234567890123456789
11-01  #10  .....####################.....#########################.....
11-02  #99  ........................................##########..........
11-03  #10  ........................#####...............................
11-04  #99  ....................................##########..............
11-05  #99  .............................................##########.....

The columns are Date, which shows the month-day portion of the relevant
day; ID, which shows the guard on duty that day; and Minute, which
shows the minutes during which the guard was asleep within the midnight
hour. (The Minute column's header shows the minute's ten's digit in the
first row and the one's digit in the second row.) Awake is shown as .,
and asleep is shown as #.

Note that guards count as asleep on the minute they fall asleep, and
they count as awake on the minute they wake up. For example, because
Guard #10 wakes up at 00:25 on 1518-11-01, minute 25 is marked as awake.

If you can figure out the guard most likely to be asleep at a specific
time, you might be able to trick that guard into working tonight so you
can have the best chance of sneaking in. You have two strategies for
choosing the best guard/minute combination.

Strategy 1: Find the guard that has the most minutes asleep. What minute
does that guard spend asleep the most?

In the example above, Guard #10 spent the most minutes asleep, a total of
50 minutes (20+25+5), while Guard #99 only slept for a total of 30 minutes
(10+10+10). Guard #10 was asleep most during minute 24 (on two days,
whereas any other minute the guard was asleep was only seen on one day).

While this example listed the entries in chronological order, your
entries are in the order you found them. You'll need to organize them
before they can be analyzed.

What is the ID of the guard you chose multiplied by the minute you
chose? (In the above example, the answer would be 10 * 24 = 240.)

"""

import collections
import datetime
import re
import sys


#[1518-09-25 00:28] falls asleep
_DATE_REGEXP = re.compile(r'\[(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)]')
#[1518-10-14 00:00] Guard #2927 begins shift
_GUARD_REGEXP = re.compile(r' *Guard #(\d+) (.*)$')

Event = collections.namedtuple('Event', 'date, time, guard, what')

def EventCmp(a, b):
  if a.date < b.date:
    return -1
  if a.date > b.date:
    return 1
  if a.time < b.time:
    return -1
  if a.time > b.time:
    return 1
  return a.what < b.what


def ParseEntry(s):
  # [1518-09-29 00:35] falls asleep
  # [1518-09-25 00:28] falls asleep
  # [1518-10-14 00:00] Guard #2927 begins shift
  m = _DATE_REGEXP.match(s)
  if not m:
    raise ValueError('No date in: "%s"' % s)
  d = datetime.date(int(m.group(1)),int(m.group(2)),int(m.group(3)))
  time = int(m.group(4)) * 60 + int(m.group(5))
  rest = s[19:]
  rest_m = _GUARD_REGEXP.match(rest)
  guard = 0
  if rest_m:
    guard = int(rest_m.group(1))
    rest = rest_m.group(2)
  e = Event(date=d, time=time, guard=guard, what=rest)
  # print('%s -> %s' % (s, e))
  return e
 

def ReadInput(inp):
  ret = []
  for line in inp:
    ret.append(ParseEntry(line.strip()))
  return sorted(ret, cmp=EventCmp)
  return ret


sleep_by_guard = {}

def RecordSleep(g, s_e, w_e):
  sg = sleep_by_guard.get(g) or ([0] * 24 * 60)
  t = s_e.time
  while t != w_e.time:
    sg[t] += 1
    t += 1
    if t == 24 * 60:
      t = 0
  sleep_by_guard[g] = sg


def Load(inp):
  entries = ReadInput(inp)
  # sleep_by_guard = collections.defaultdict(int)
  g = 0
  for e in entries:
    # print e
    if e.guard > 0:
      g = e.guard 
      sleep_event = None
    if e.what == 'falls asleep':
      sleep_event = e
    elif e.what == 'wakes up':
      RecordSleep(g, sleep_event, e)

def part1():
  g_top = 0
  g_most = 0
  for g in sleep_by_guard:
    tot_sleep = sum(sleep_by_guard[g])
    if tot_sleep > g_most:
      g_top = g
      g_most = tot_sleep
  print 'guard %d most sleep at %d' % (g_top, g_most)
  best_min = 0
  best_min_v = 0
  mv = sleep_by_guard[g_top]
  for m in range(24 * 60):
    if mv[m] > best_min_v:
      best_min = m
      best_min_v = mv[m]
  print 'guard %d best min is %d at %d' % (g_top, best_min, best_min_v)
  print 'ans=%d' % (g_top * best_min)

def part2():
  g_most = 0
  m_most = 0
  m_most_v = 0
  for g in sleep_by_guard:
    mv = sleep_by_guard[g]
    for m in range(24 * 60):
      if mv[m] > m_most_v:
        g_most = g
        m_most = m
        m_most_v = mv[m]
  print 'ans=%d' % (g_most * m_most)


with open(sys.argv[1]) as inp:
  Load(inp)
  part2()
