# -*- coding: utf-8 -*-

import os
import json
import pika
import pycapo
import sys


def epilogue():
    # as a little hack
    if not 'CAPO_PROFILE' in os.environ:
        # try to synthesize a profile from our installation root
        pathBreakdown = os.path.abspath(sys.argv[0]).split(os.path.sep)
        #CV sticks an extra subdirectory into the installation
        if pathBreakdown[-3] == 'current':
            profile = pathBreakdown[-4]
        else:
            profile = pathBreakdown[-3]
        os.environ['CAPO_PROFILE'] = profile
        print('No CAPO_PROFILE, synthesizing {0} by path'.format(str(profile)))

    error_code = sys.argv[10]
    # figure out how to connect to AMQP using Capo
    capo = pycapo.CapoConfig()
    hostname = capo.getstring('edu.nrao.archive.configuration.AmqpServer.hostname')
    username = capo.getstring('edu.nrao.archive.configuration.AmqpServer.username')
    password = capo.getstring('edu.nrao.archive.configuration.AmqpServer.password')

    # connect
    credentials = pika.PlainCredentials(username, password)
    conn = pika.BlockingConnection(
        pika.ConnectionParameters(hostname, credentials=credentials))
    channel = conn.channel()

    try:
        # make the exchange we need
        channel.exchange_declare('archive.job-status', 'topic', durable=True)

        # build the message
        job_id = sys.argv[1]
        message = json.dumps({'pbsJobId': job_id,
                              'status': {'status': 'SUCCESS' if error_code == '0' else 'FAILURE',
                                         'result': {'error_code': error_code},
                                         'sender': 'epilogue'}})

        # dispatch it
        channel.basic_publish(exchange='archive.job-status', routing_key=job_id, body=message)
    finally:
        channel.close()
        conn.close()