#include "UserPaths.h"
#include <wx/dir.h>
#include <wx/log.h>

namespace TD {

// Copy one file, leaving the original alone if anything goes wrong. We COPY
// rather than move: if the install directory turns out to be read-only we
// cannot delete from it anyway, and leaving the original in place is harmless.
static bool CopyIfAbsent(const wxString& src, const wxString& dstDir) {
    wxFileName fn(src);
    wxString dst = dstDir + wxFileName::GetPathSeparator() + fn.GetFullName();
    if (wxFileName::FileExists(dst)) return false;   // already migrated
    return wxCopyFile(src, dst, /*overwrite=*/false);
}

void MigrateLegacyUserFiles() {
    const wxString install = InstallDir();
    const wxString userDir = UserDataDir();

    // If the app happens to be running FROM the user folder there is nothing
    // to migrate, and copying a file onto itself would be a mess.
    if (wxFileName(install).SameAs(wxFileName(userDir))) return;

    int moved = 0;

    // ── Layouts: *.tdl and the older *.xml, sitting beside the exe ──────────
    {
        wxArrayString files;
        wxDir::GetAllFiles(install, &files, "*.tdl", wxDIR_FILES);
        wxDir::GetAllFiles(install, &files, "*.xml", wxDIR_FILES);
        for (const auto& f : files) {
            // catalog.xml is app data, not a layout -- leave it where it is.
            wxFileName fn(f);
            if (fn.GetFullName().IsSameAs("catalog.xml", false)) continue;
            if (CopyIfAbsent(f, userDir)) ++moved;
        }
    }

    // ── Library blocks: <install>/library/<system>/*.tdl ────────────────────
    {
        wxString legacyLib = install + wxFileName::GetPathSeparator() + "library";
        if (wxFileName::DirExists(legacyLib)) {
            wxString destLib = UserLibraryDir();

            wxDir dir(legacyLib);
            wxString sub;
            bool more = dir.GetFirst(&sub, wxEmptyString, wxDIR_DIRS);
            while (more) {
                wxString srcSub  = legacyLib + wxFileName::GetPathSeparator() + sub;
                wxString destSub = destLib   + wxFileName::GetPathSeparator() + sub;
                if (!wxFileName::DirExists(destSub))
                    wxFileName::Mkdir(destSub, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);

                wxArrayString blocks;
                wxDir::GetAllFiles(srcSub, &blocks, "*.tdl", wxDIR_FILES);
                for (const auto& b : blocks)
                    if (CopyIfAbsent(b, destSub)) ++moved;

                more = dir.GetNext(&sub);
            }
        }
    }

    if (moved > 0) {
        wxLogMessage("Track Designer: moved %d file(s) from the install folder "
                     "to %s", moved, userDir);
    }
}

} // namespace TD
