#!/usr/bin/env python

import sys, os, exceptions
import time, datetime

# which is better?
# All numeric. Should do month names and abbrevs.
# Default is year, month, day of today
# prog [day [month [year]]]
# prog [year [month [day]]]
# prog [-y year] [-m month] [-d day]
#
# dtd = datetime.date(2010, 8, 8)

# e.g. datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
##del# class TZ(datetime.tzinfo):
##del#     def __init__(self, tz_seconds=time.timezone):
##del#         self.tz_seconds = tz_seconds
##del#         print "self.tz_seconds", self.tz_seconds
##del#     def utcoffset(self, dt):
##del#         return datetime.timedelta(seconds=self.tz_seconds)

class DynamicLocalTZinfo(datetime.tzinfo):
    """Fixed offset in minutes east from UTC."""

    def __init__(self, offset=None, tzname=None, dst_name=None,
                 dst_offset=None):
        if offset is not None:
            self.d_offset = datetime.timedelta(seconds = offset)
        else:
            self.d_offset = datetime.timedelta(seconds = -time.timezone)

        if dst_offset is not None:
            self.d_dst_offset = dst_offset
        else:
            if time.daylight:
                self.d_dst_offset = datetime.timedelta(seconds = -time.altzone)
            else:
                self.d_dst_offset = datetime.timedelta(self.d_offset)
        self.d_dst_diff = self.d_dst_offset - self.d_offset
        tmp_tzname, tmp_dst_name =  time.tzname

        if tzname is not None:
            self.d_tzname = tzname
        else:
            self.d_tzname = tmp_tzname
        if dst_name is not None:
            self.d_dst_name = dst_name
        else:
            self.d_dst_name = tmp_dst_name

    def utcoffset(self, dt):
        if self._isdst(dt):
            return self.d_dst_offset
        else:
            return self.d_offset

    def tzname(self, dt):
        return self.d_tzname

    def dst(self, dt):
        if self.dst_p(dt):
            return self.d_dst_diff
        else:
            return 0

    def dst_p(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, -1)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0

    def __repr__(self):
        ret = []
        ret.append("name: %s" % (self.d_tzname,))
        ret.append("offset: %s" % (self.d_offset,))
        ret.append("dst name: %s" % (self.d_dst_name,))
        ret.append("dst offset: %s" % (self.d_dst_offset,))
        ret.append("dst diff: %s" % (self.d_dst_diff,))

        return ", ".join(ret)

def eval_date_component(parameter_value, parameter_string, parameter_name):
    pval0 = parameter_value
    isa_delta_p = parameter_string[0] in ('+', '-')
    parameter = eval(parameter_string)
    if isa_delta_p:
        part2 = "%s + %s" % (pval0, parameter)
        parameter += parameter_value
    else:
        part2 = "%s" % (parameter,)
    if parameter <= 0:
        raise exceptions.ValueError(
            "Error computing date component: %s: %s is <= 0" % (
                parameter_name, part2))
    return parameter

def main(argv):
    import getopt
    verbosity = 0
    today_ymd = time.localtime()[0:3]
    year, month, day = today_ymd

    opt_string = "y:m:d:v"
    opts, args = getopt.getopt(argv[1:], opt_string)
    for o, v in opts:
        if o == '-v':
            verbosity += 1
            continue
        if o == '-y':
            year = eval_date_component(year, v, "year")
            continue
        if o == '-m':
            month = eval_date_component(month, v, "month")
            continue
        if o == '-d':
            day = eval_date_component(day, v, "day")
            continue
    ymd = (year, month, day)
    suffix = ""
    if verbosity > 0:
        suffix = "desired: %s" % (ymd,)
        if verbosity > 1:
            suffix += ", today: %s" % (today_ymd,)

    datetime_date = datetime.datetime(*ymd,
                                      tzinfo=DynamicLocalTZinfo())
    iso_cal = datetime_date.isocalendar()
    if verbosity:
        print "iso_cal:", iso_cal
    week_of_year = iso_cal[1]
    if suffix != "":
        suffix = " " + suffix

    print "%s%s" % (week_of_year, suffix)

if __name__ == "__main__":
    try:
        main(sys.argv)
    except exceptions.Exception, e:
        print >>sys.stderr, "Exception:", " ".join([str(x) for x in e])

    sys.exit(0)
