#!/usr/bin/env python3

import os

# Start coverage if set in previous process
if os.environ.get('SITE_COVERAGE'):
    import coverage
    cov = coverage.coverage(branch=True, include='app/*')
    cov.start()

from flask.ext.assets import ManageAssets
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager

from app import create_app, db


app = create_app(os.getenv('SITE_CONFIG', 'default'))

manager = Manager(app)
migrate = Migrate(app, db)

manager.add_command('assets', ManageAssets)
manager.add_command('db', MigrateCommand)


@manager.command
def test(coverage=False):
    if coverage and not os.environ.get('SITE_COVERAGE'):
        restart_with_coverage()

    import pytest
    pytest.main(['-x', 'tests'])

    if coverage:
        stop_coverage()
        save_coverage()


def restart_with_coverage():
    import sys
    os.environ['SITE_COVERAGE'] = '1'
    os.execvp(sys.executable, [sys.executable] + sys.argv)


def stop_coverage():
    cov.stop()
    print('\nCOVERAGE SUMMARY\n================')
    cov.report()


def save_coverage():
    basedir = os.path.abspath(os.path.dirname(__file__))
    covdir = os.path.join(basedir, 'tests', 'coverage')
    cov.html_report(directory=covdir)
    print('\nHTML report saved to {}/index.html'.format(covdir))


if __name__ == '__main__':
    manager.run()
