module.exports = function (grunt) {

    var path = require('path'),

        HANDLEBARS_LIB       = path.join(process.cwd(), '../../../', 'handlebars.js/lib'),
        PREPENDED_COMMENT    = '/* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */\n',
        REMOVE_EXPORTS_REGEX = /^\/\/ BEGIN\(BROWSER\)$\s*([\s\S]*)^\/\/ END\(BROWSER\)$/m,

        BASE_FILES = [
            'handlebars/base.js',
            'handlebars/utils.js',
            'handlebars/runtime.js'
        ],

        COMPILER_FILES = [
            'handlebars/compiler/parser.js',
            'handlebars/compiler/base.js',
            'handlebars/compiler/ast.js',
            'handlebars/compiler/compiler.js'
        ];

    function importFiles(files, prefix) {
        prefix || (prefix = '');

        files.forEach(function (file) {
            var src  = path.join(HANDLEBARS_LIB, file),
                dest = path.join('js', prefix + path.basename(file));

            if (!grunt.file.exists(src)) {
                grunt.fail.fatal('Did you build Handlebars.js yet?');
            }

            grunt.log.writeln('Importing: '.green + file.cyan + ' to ' + dest.cyan);
            grunt.file.write(dest, processFile(src));
        });
    }

    function processFile(file) {
        var contents = grunt.file.read(file),
            processed;

        // Processes the raw file by adding a the "this is a build file"
        // comment, and remove the module exports from the contents of the file.
        // This also trims the file and makes sure it ends with a newline char.
        processed = [
            PREPENDED_COMMENT,
            removeExports(contents).trim(),
            ''
        ].join('\n');

        return processed;
    }

    function removeExports(contents) {
        var match = contents.match(REMOVE_EXPORTS_REGEX);
        return match ? match[1] : contents;
    }

    // -- Tasks ----------------------------------------------------------------

    grunt.registerTask('find', 'Find Handlebars.js project for import.', function () {
        grunt.log.write('Looking for Handlebars.js...'.green);

        if (!grunt.file.exists(HANDLEBARS_LIB)) {
            grunt.log.writeln('');
            grunt.fail.fatal(
                'Could not locate Handlebars repo: ' + HANDLEBARS_LIB +
                '\nDid you clone it above the yui3 repo?');
        }

        grunt.log.writeln('found: '.white + HANDLEBARS_LIB.cyan);
    });

    grunt.registerTask('clean', 'Delete imported Handlebars source files.', function () {
        var files = grunt.file.expand('js/handlebars-*.js');

        files.forEach(function (file) {
            grunt.log.writeln('Deleting: '.red + file.cyan);
            grunt.file['delete'](file);
        });
    });

    grunt.registerTask('import-base', 'Import Handlebars base source files.', function () {
        importFiles(BASE_FILES, 'handlebars-');
    });

    grunt.registerTask('import-compiler', 'Import Handlebars compiler source files.', function () {
        importFiles(COMPILER_FILES, 'handlebars-compiler-');
    });

    grunt.registerTask('import', [
        'import-base',
        'import-compiler'
    ]);

    grunt.registerTask('all', [
        'find',
        'clean',
        'import'
    ]);

    grunt.registerTask('default', ['all']);
};
