#include "replace_dist_arrays_in_io.h"

#include "../ParallelizationRegions/resolve_par_reg_conflicts.h"

#include <string>
#include <map>
#include <set>
#include <ExpressionTransform/expr_transform.h>

using std::map;
using std::set;
using std::string;
using std::vector;
using std::to_string;
using std::make_pair;
using std::pair;

#define DEBUG_TRACE 0

static void findArrays(SgExpression* exp, set<SgSymbol*>& arrays)
{
    if (exp)
    {
        if (isArrayRef(exp))
            arrays.insert(exp->symbol());

        findArrays(exp->lhs(), arrays);
        findArrays(exp->rhs(), arrays);
    }
}

static void populateDistributedIoArrays(map<SgSymbol*, set<SgStatement*>>& arrays, SgStatement* stat)
{
    auto var = stat->variant();

    if (var != READ_STAT && var != PRINT_STAT && var != WRITE_STAT)
        return;

    // check if such IO allowed in dvm: 
    // list should consist only of single array and format string should be *

    bool need_replace = false;

    SgExpression* ioList = stat->expr(0);

    if (!ioList)
        return;

    if (ioList->variant() != EXPR_LIST)
        return;

    if (ioList->rhs() == NULL)
    {
        SgExpression* arg = ioList->lhs();
        if (!arg)
            return;

        if (!isArrayRef(arg))
            return;

        if (arg->lhs())
            need_replace = true;
    }
    else
    {
        need_replace = true;
    }

    if (!need_replace)
    {
        switch (var)
        {
        case PRINT_STAT:
        {
            SgExpression* fmt = stat->expr(1);
            if (!fmt || fmt->variant() != SPEC_PAIR || fmt->lhs()->variant() != KEYWORD_VAL)
            {
                printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
                return;
            }

            if (fmt->rhs()->variant() != KEYWORD_VAL || fmt->rhs()->sunparse() != "*")
                need_replace = true;


            break;
        }
        case READ_STAT:
        case WRITE_STAT:
        {

            SgExpression* spec = stat->expr(1);
            __spf_print(DEBUG_TRACE, "[%d: %s (%d)]\n", 2000, spec->rhs()->unparse(), spec->rhs()->variant());
            if (!spec || spec->variant() != EXPR_LIST ||
                spec->lhs()->variant() != SPEC_PAIR ||
                !spec->rhs() || !spec->rhs()->lhs() || spec->rhs()->lhs()->variant() != SPEC_PAIR)
            {
                printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
                return;
            }

            SgExpression* unit_val = spec->lhs()->rhs(), * fmt_val = spec->rhs()->lhs()->rhs();

            if (unit_val->variant() != KEYWORD_VAL || unit_val->sunparse() != "*" ||
                fmt_val->variant() != KEYWORD_VAL || fmt_val->sunparse() != "*")
                need_replace = true;

            break;
        }
        default:
            break;
        }
    }

    if (!need_replace)
        return;

    set<SgSymbol*> found_arrays;

    for (int i = 0; i < 3; i++)
        findArrays(stat->expr(i), found_arrays);

    for (auto* by_symb : found_arrays)
    {
        string array_name = string(by_symb->identifier());
        DIST::Array* array_p = getArrayFromDeclarated(declaratedInStmt(by_symb), array_name);
        if (array_p && array_p->GetDistributeFlagVal() == Distribution::distFlag::IO_PRIV && arrays[by_symb].insert(stat).second)
            __spf_print(DEBUG_TRACE, "[%d]: add array %s\n", stat->lineNumber(), array_p->GetName().c_str());
    }

    __spf_print(DEBUG_TRACE, "[replace]\n");
}

static void replaceArrayRec(SgSymbol* arr, SgSymbol* replace_by, SgExpression* exp, bool& has_read, bool& has_write, bool from_read, bool from_write)
{
    if (!exp)
        return;

    if (exp->symbol() && exp->symbol()->identifier() && strcmp(exp->symbol()->identifier(), arr->identifier()) == 0)
    {
        has_read |= from_read;
        has_write |= from_write;
        exp->setSymbol(replace_by);
    }

    switch (exp->variant())
    {
    case FUNC_CALL:
    {
        replaceArrayRec(arr, replace_by, exp->rhs(), has_read, has_write, true, false);
        replaceArrayRec(arr, replace_by, exp->lhs(), has_read, has_write, true, true);
        break;
    }
    case EXPR_LIST:
    {
        replaceArrayRec(arr, replace_by, exp->lhs(), has_read, has_write, from_read, from_write);
        replaceArrayRec(arr, replace_by, exp->rhs(), has_read, has_write, from_read, from_write);
        break;
    }
    default:
    {
        replaceArrayRec(arr, replace_by, exp->lhs(), has_read, has_write, true, false);
        replaceArrayRec(arr, replace_by, exp->rhs(), has_read, has_write, true, false);
        break;
    }
    }
}

static void replaceArrayRec(SgSymbol* arr, SgSymbol* replace_by, SgStatement* st, bool& has_read, bool& has_write)
{
    if (!st)
        return;

    switch (st->variant())
    {
    case ASSIGN_STAT:
    case READ_STAT:
    {
        replaceArrayRec(arr, replace_by, st->expr(0), has_read, has_write, false, true);
        replaceArrayRec(arr, replace_by, st->expr(1), has_read, has_write, true, false);
        break;
    }
    case PROC_STAT:
    case FUNC_STAT:
    {
        replaceArrayRec(arr, replace_by, st->expr(0), has_read, has_write, true, false);
        replaceArrayRec(arr, replace_by, st->expr(1), has_read, has_write, true, true);
        break;
    }
    default:
    {
        for (int i = 0; i < 3; i++)
            replaceArrayRec(arr, replace_by, st->expr(i), has_read, has_write, true, false);

        break;
    }
    }
}

static void copyArrayBetweenStatements(SgSymbol* replace_symb, SgSymbol* replace_by, SgStatement* start, SgStatement* last, bool start_is_scope)
{
    while (start->lexNext() && !isSgExecutableStatement(start->lexNext()))
        start = start->lexNext();

    auto* stop = last->lexNext();

    bool has_read = false, has_write = false;

    for (auto* st = start->lexNext(); st && st != stop->lexPrev(); st = st->lexNext())
        replaceArrayRec(replace_symb, replace_by, st, has_read, has_write);


    if (has_read)
    {
        // A_copy = A
        SgAssignStmt* assign = new SgAssignStmt(*new SgArrayRefExp(*replace_by), *new SgArrayRefExp(*replace_symb));
        assign->setlineNumber(getNextNegativeLineNumber()); // before region
        auto* parent = start_is_scope ? start : start->controlParent();
        if (parent && parent->lastNodeOfStmt() == start)
            parent = parent->controlParent();

        start->insertStmtAfter(*assign, *parent);
    }

    if (has_write)
    {
        // A = A_reg
        SgAssignStmt* assign = new SgAssignStmt(*new SgArrayRefExp(*replace_symb), *new SgArrayRefExp(*replace_by));
        //TODO: bug with insertion
        //assign->setlineNumber(getNextNegativeLineNumber()); // after region
        last->insertStmtBefore(*assign, *(last->controlParent()));
    }
}

static void replaceArrayInFragment(SgSymbol* replace_symb, const set<SgStatement*> usages, SgSymbol* replace_by, SgStatement* start, SgStatement* last, const string& filename)
{
    while (start->lexNext() && !isSgExecutableStatement(start->lexNext()))
        start = start->lexNext();

    set<SgStatement*> not_opened, not_closed, copied;

    for (auto* it = start; it; it = it->controlParent())
        not_opened.insert(it);

    for (auto* it = last; it; it = it->controlParent())
        not_closed.insert(it);

    for (auto* io_stmt : usages)
    {
        bool already_copied = false;
        SgStatement* copy_scope = NULL;

        for (auto* par = io_stmt; par; par = par->controlParent())
        {
            if (copied.find(par) != copied.end())
            {
                already_copied = true;
                break;
            }
            else if (not_opened.find(par) != not_opened.end() || not_closed.find(par) != not_closed.end())
            {
                copy_scope = par;
                break;
            }
        }


        if (already_copied)
            continue;

        auto* scope_start = copy_scope, * scope_end = copy_scope->lastNodeOfStmt();
        __spf_print(DEBUG_TRACE, "[scope to copy] %d\n", copy_scope->lineNumber());

        if (not_opened.find(copy_scope) != not_opened.end() && start != copy_scope)
        {
            auto* from = start;
            for (auto* st = from; st; st = st->controlParent())
            {
                __spf_print(DEBUG_TRACE, "[find start of parent %d] %d\n", copy_scope->lineNumber(), st->lineNumber());

                if (st->controlParent() == copy_scope)
                {
                    scope_start = st->lastNodeOfStmt() ? st->lastNodeOfStmt() : st;
                    break;
                }
            }
        }

        if (not_closed.find(copy_scope) != not_closed.end() && last != copy_scope)
        {
            for (auto* st = last; st; st = st->controlParent())
            {
                __spf_print(DEBUG_TRACE, "[find end of parent %d] %d\n", copy_scope->lineNumber(), st->lineNumber());

                if (st->controlParent() == copy_scope)
                {
                    scope_end = st;
                    break;
                }
            }
        }

        __spf_print(DEBUG_TRACE, "[copy %s] [%d, %d]\n", replace_symb->identifier(), scope_start->lineNumber(), scope_end->lineNumber());
        copyArrayBetweenStatements(replace_symb, replace_by, scope_start, scope_end, copy_scope == scope_start);
        copied.insert(copy_scope);
    }
}

static bool ioReginBorder(SgStatement* stat, SgStatement* last_io_bound)
{
    auto var = stat->variant();

    static const set<int> border_stats =
    {
        PROC_STAT,
        FUNC_STAT,
        PROG_HEDR,
        FUNC_HEDR,
        PROC_HEDR,
        FOR_NODE,
        LOOP_NODE,
        RETURN_NODE,
        RETURN_STAT,
        STOP_STAT,
        STOP_NODE,
        EXIT_STMT,
        EXIT_NODE
    };

    if (border_stats.find(var) != border_stats.end())
        return true;

    if (last_io_bound && last_io_bound->lastNodeOfStmt() && last_io_bound->lastNodeOfStmt() == stat)
        return true;

    int parent_var;

    if (var == CONTROL_END && border_stats.find(stat->controlParent()->variant()) != border_stats.end())
        return true;

    return false;
}

void replaceDistributedArraysInIO(vector<ParallelRegion*>& regions,
    const map<string, vector<FuncInfo*>>& allFuncInfo,
    map<string, vector<Messages>>& SPF_messages,
    map<string, map<int, set<string>>>& newDeclsToInclude)
{
    map<SgSymbol*, SgSymbol*> created_copies;
    map<string, map<int, set<string>>> copied_syms;

    for (auto& region : regions)
    {
        __spf_print(DEBUG_TRACE, "[%s]: enter region\n", region->GetName().c_str());

        for (auto& linesByFile : region->GetAllLinesToModify())
        {
            const auto& filename = linesByFile.first;

            if (SgFile::switchToFile(filename) < 0)
            {
                printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
                return;
            }

            for (auto& lines : linesByFile.second)
            {
                __spf_print(DEBUG_TRACE, "[fragment] %s: %d:%d %d\n", filename.c_str(), lines.lines.first,
                    lines.lines.second, lines.isImplicit());

                SgStatement* curr_stmt, * end;

                if (lines.isImplicit())
                {

                    curr_stmt = current_file->SgStatementAtLine(lines.lines.first);
                    end = current_file->SgStatementAtLine(lines.lines.second);

                    if (end)
                        end = end->lexNext();
                }
                else
                {
                    curr_stmt = lines.stats.first->GetOriginal();
                    end = lines.stats.second->GetOriginal()->lexNext();
                }

                map<SgSymbol*, set<SgStatement*>> need_replace;
                SgStatement* last_io_bound = NULL;


                while (curr_stmt != end)
                {
                    if (!curr_stmt)
                        break;

                    auto var = curr_stmt->variant();


                    if (var == PROC_HEDR || var == PROG_HEDR || var == FUNC_HEDR)
                    {
                        curr_stmt = curr_stmt->lexNext();
                        while (curr_stmt && !isSgExecutableStatement(curr_stmt))
                        {
                            last_io_bound = curr_stmt;
                            curr_stmt = curr_stmt->lexNext();
                        }

                        if (!curr_stmt)
                            break;
                    }

                    if (ioReginBorder(curr_stmt, last_io_bound))
                    {
                        for (const auto& by_array_to_copy : need_replace)
                        {
                            auto* array_to_copy = by_array_to_copy.first;
                            auto it = created_copies.find(array_to_copy);

                            if (it == created_copies.end())
                            {
                                string array_name = string(array_to_copy->identifier());
                                DIST::Array* array_p = getArrayFromDeclarated(declaratedInStmt(array_to_copy), array_name);

                                bool fromModule = (array_p->GetLocation().first == DIST::l_MODULE);
                                const string locationName = array_p->GetLocation().second;

                                auto place = *array_p->GetDeclInfo().begin();
                                string fileName = place.first;
                                string suffix = "_io_l";

                                if (fromModule)
                                    suffix = "_io_m";

                                pair<SgSymbol*, SgSymbol*> copied;
                                copied.first = array_to_copy;

                                if (SgFile::switchToFile(fileName) == -1)
                                {
                                    auto* func_stmt = curr_stmt->getScopeForDeclare();

                                    SgStatement* insertPlace = NULL;
                                    for (auto iterator = func_stmt->lexNext();
                                        !isSgExecutableStatement(iterator) || isSPF_stat(iterator) &&
                                        !(iterator->variant() == SPF_PARALLEL_REG_DIR || iterator->variant() == SPF_END_PARALLEL_REG_DIR);
                                        iterator = iterator->lexNext())
                                    {
                                        insertPlace = iterator;
                                    }

                                    //NULL - no decl stats in function!
                                    if (!insertPlace)
                                        insertPlace = func_stmt;

                                    auto st = insertPlace->controlParent();
                                    if (st->variant() == GLOBAL)
                                        st = insertPlace;

                                    auto& copied_symb = array_to_copy->copy();
                                    copied.second = &copied_symb;

                                    auto new_name = string(array_to_copy->identifier()) + "_io_c";
                                    copied_symb.changeName(new_name.c_str());

                                    auto stat = array_to_copy->makeVarDeclStmt();
                                    auto res = CalculateInteger(stat->expr(0)->copyPtr());
                                    res->lhs()->setSymbol(copied_symb);
                                    stat->setExpression(0, res);

                                    insertPlace->insertStmtAfter(*stat, *st);
                                }
                                else
                                {
                                    copied = copyArray(place, array_p, linesByFile.second, suffix + to_string(region->GetId()), fileName, newDeclsToInclude, copied_syms);
                                }

                                SgStatement* decl = SgStatement::getStatementByFileAndLine(place.first, place.second);

                                if (decl)
                                    decl = decl->lexNext();

                                if (decl)
                                {
                                    string dir_str;
                                    if (decl->comments())
                                    {
                                        string str_comment = string(decl->comments());
                                        if (str_comment.size() && str_comment.back() != '\n')
                                            dir_str += "\n";
                                    }

                                    dir_str += "!$SPF ANALYSIS(PROCESS_PRIVATE(" + string(copied.second->identifier()) + "))\n";
                                    decl->addComment(dir_str.c_str());
                                }
                                created_copies.insert({ array_to_copy, copied.second });
                            }
                        }

                        if (last_io_bound)
                        {
                            __spf_print(DEBUG_TRACE, "[io region] [%d, %d]\n", last_io_bound->lineNumber(), curr_stmt->lineNumber());

                            for (const auto& p : need_replace)
                            {
                                auto it = created_copies.find(p.first);
                                if (it != created_copies.end())
                                    replaceArrayInFragment(p.first, p.second, it->second, last_io_bound, curr_stmt, filename);
                                else
                                {
                                    printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
                                    return;
                                }
                            }
                        }

                        need_replace.clear();
                        last_io_bound = curr_stmt;
                    }

                    __spf_print(DEBUG_TRACE, "[line] %d (%d)\n", curr_stmt->lineNumber(), curr_stmt->variant());

                    for (int i = 0; i < 3; i++)
                    {
                        if (curr_stmt->expr(i))
                        {
                            __spf_print(DEBUG_TRACE, "[%d: %s (%d)]\n", i, curr_stmt->expr(i)->unparse(), curr_stmt->expr(i)->variant());
                        }
                    }

                    populateDistributedIoArrays(need_replace, curr_stmt);
                    curr_stmt = curr_stmt->lexNext();
                }
            }
        }
    }
}
