import re
import sys
import psycopg2
from datetime import datetime

dqe_txt_re = re.compile(r"\s*([\d/]+)\s+([\d.]+)\s+[+-]?\s+[\d.-]+\s+\d+\s+[+-]?\s+[\d-]+\s+(\d+)\s+(\d+)")
dbh = psycopg2.connect(database = "rain")
curs = dbh.cursor()

data = sys.stdin.readlines()
for buf in data:
  m = dqe_txt_re.match(buf)
  if not m:
#    print "No match: ", buf
    continue
  (date, usage_kwh, temp_f_low, temp_f_high) = m.groups()
  now = datetime.now()
  sqldate = datetime.strptime(date, '%m/%d')
  sqldate = sqldate.replace(year = now.year)

  if sqldate.month >= 11 and now.month <= 3:
    sqldate = sqldate.replace(year = sqldate.year - 1)

#  print "sqldate: " + str(sqldate), sqldate.year, now.year    

  print sqldate, usage_kwh, temp_f_low, temp_f_high,

  curs.execute("SELECT date FROM electricity WHERE date=%s",
               [sqldate.isoformat()])
  if curs.rowcount == 0:
    curs.execute("INSERT INTO electricity (date, kwh_used) VALUES (%s, %s)",
                 [sqldate.isoformat(), usage_kwh])
    print '*',
#  else:
#    print "Already have ", str(sqldate)

  curs.execute("SELECT date FROM temp_outdoor WHERE date=%s",
               [sqldate.isoformat()])
  if curs.rowcount == 0:
    curs.execute("INSERT INTO temp_outdoor (date, low_f, high_f) VALUES (%s, %s, %s)",
                 [sqldate.isoformat(), temp_f_low, temp_f_high])
#  else:
#    print "Already have ", str(sqldate)

  print
  dbh.commit()
