from datetime import datetime
from traceback import format_exc, extract_stack, format_list

import cardsharp as cs

from ..configuration import segment_info
from ..segment import Segment

_segments = {}
for s in segment_info.itervalues():
    _segments[s['label']] = {'label': s['label'], 
                             'id': s['id'], 
                             'region_var': s['region_var'], 
                             'priority': s['priority']}
def run(**opt):
    """Stage the data."""
    try:
        print "Begin data stage process @ %s ..." % datetime.now().isoformat(' ')
        segment = _segments[opt['segment']]
        del(opt['segment'])
        
        print "Starting %s data stage at %s" % (segment.get('label'), datetime.now().isoformat(' '))
        print "Begin load and variable processing..."
        
        s = Segment(segment.get('label'), 'stage', **opt)
        s.load_metadata_variables()         
        s.load_raw_data()
        print "Data loaded, new variables added, variable rules set."
        print """Calculating and setting max string length for original variables..."""
        s.update_metadata_var_lengths()
        cs.wait()
        
        print "Stage process complete @ %s." % datetime.now().isoformat(' ')
        return 1
    except:
        if opt['verbose']:
            raise
        return (format_exc(), format_list(extract_stack())) 