#pragma once
// ── UserPaths ────────────────────────────────────────────────────────────────
// Where the user's layouts and library blocks live.
//
// These used to be written next to the executable. That happens to work when
// the app runs from somewhere writable, but it is wrong:
//
//   * Under C:\Program Files the directory is read-only for a standard user.
//     Saving fails, or Windows silently redirects the write into a hidden
//     VirtualStore folder where the user can never find their files again.
//   * Uninstalling the app can take the user's layouts with it.
//   * Every user on the machine shares one folder.
//   * It is not where anyone would think to look.
//
// So layouts now live in the platform's documents folder:
//
//   Windows   C:\Users\<name>\Documents\Track Designer\
//   macOS     ~/Documents/Track Designer/
//
// wxStandardPaths gives us that portably, which matters for the Mac build.
// ─────────────────────────────────────────────────────────────────────────────
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include <wx/string.h>

namespace TD {

// The user's Track Designer folder, created if it does not exist.
// Falls back to the executable's directory if the documents folder cannot
// be created for some reason -- better to save somewhere than nowhere.
inline wxString UserDataDir() {
    static wxString cached;
    if (!cached.empty()) return cached;

    wxString docs = wxStandardPaths::Get().GetDocumentsDir();
    wxString dir  = docs + wxFileName::GetPathSeparator() + "Track Designer";

    if (!wxFileName::DirExists(dir))
        wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);

    if (!wxFileName::DirExists(dir)) {
        // Could not create it -- fall back to beside the executable.
        wxFileName exe(wxStandardPaths::Get().GetExecutablePath());
        dir = exe.GetPath();
    }

    cached = dir;
    return cached;
}

// The library-blocks folder: <UserDataDir>/library
inline wxString UserLibraryDir() {
    wxString dir = UserDataDir() + wxFileName::GetPathSeparator() + "library";
    if (!wxFileName::DirExists(dir))
        wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
    return dir;
}

// Where the app is installed. Layouts and blocks that shipped with an older
// version still live here, so we migrate them out on first run.
inline wxString InstallDir() {
    wxFileName exe(wxStandardPaths::Get().GetExecutablePath());
    return exe.GetPath();
}

// One-time migration: move any layouts and library blocks that an earlier
// version left beside the executable into the user's folder, so nobody loses
// their work when they upgrade. Safe to call on every launch -- it copies only
// files that are not already at the destination, and does nothing once the
// install directory has been emptied of them.
void MigrateLegacyUserFiles();

} // namespace TD
