/* Copyright (C) 2004-2022 J.F.Dockes
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#ifndef _DB_H_INCLUDED_
#define _DB_H_INCLUDED_

#include <stdint.h>
#include <string>
#include <vector>
#include <memory>

// rcldb defines an interface for a 'real' text database. The current 
// implementation uses xapian only, and xapian-related code is in rcldb.cpp
// If support was added for other backend, the xapian code would be moved in 
// rclxapian.cpp, another file would be created for the new backend, and the
// configuration/compile/link code would be adjusted to allow choosing. There 
// is no plan for supporting multiple different backends.
// 
// In no case does this try to implement a useful virtualized text-db interface
// The main goal is simplicity and good matching to usage inside the recoll
// user interface. In other words, this is not exhaustive or well-designed or 
// reusable.
//
// Unique Document Identifier: uniquely identifies a document in its
// source storage (file system or other). Used for up to date checks
// etc. "udi". Our user is responsible for making sure it's not too
// big, cause it's stored as a Xapian term (< 150 bytes would be
// reasonable)

class RclConfig;
class Aspell;
struct FieldTraits;
class SynGroups;

namespace Rcl {

class Doc;
class StopList;

// Omega compatible values. We leave a hole for future omega values. Not sure 
// it makes any sense to keep any level of omega compat given that the index
// is incompatible anyway.
enum value_slot {
    // Omega-compatible values:
    VALUE_LASTMOD = 0,  // 4 byte big endian value - seconds since 1970.
    VALUE_MD5 = 1,      // 16 byte MD5 checksum of original document.
    VALUE_SIZE = 2,     // sortable_serialise(<file size in bytes>)

    ////////// Recoll only:
    // Doc sig as chosen by app (ex: mtime+size
    VALUE_SIG = 10,
};

class SearchData;
class TermIter;
class Query;

/** Used for returning result lists for index terms matching some criteria */
class TermMatchEntry {
public:
    TermMatchEntry() {}
    TermMatchEntry(const std::string& t, int f, int d)
        : term(t), wcf(f), docs(d) {}
    TermMatchEntry(const std::string& t)
        : term(t) {}
    bool operator==(const TermMatchEntry &o) const { 
        return term == o.term;
    }
    bool operator<(const TermMatchEntry &o) const { 
        return term < o.term;
    }

    std::string term;
    int    wcf{0}; // Total count of occurrences within collection.
    int    docs{0}; // Number of documents countaining term.
};

/** Term match result list header: statistics and global info */
class TermMatchResult {
public:
    TermMatchResult(bool strip_prefixes = false) : m_prefix_stripped(strip_prefixes) {
        clear();
    }
    void clear() {
        entries.clear(); 
    }
    bool m_prefix_stripped;
    // Term expansion
    std::vector<TermMatchEntry> entries;
    // If a field was specified, this is the corresponding index prefix
    std::string prefix;
    // Terms generated by spelling proximity: used to inform the user (transmitted through
    // Highlightdata)
    std::vector<std::string> fromspelling;
};

class DbStats {
public:
    DbStats() {}
    // Index-wide stats
    unsigned int dbdoccount{0};
    double       dbavgdoclen{0};
    size_t       mindoclen{0};
    size_t       maxdoclen{0};
    std::vector<std::string> failedurls; /* Only set if requested */
};


/**
 * Wrapper class for the native database.
 */
class Db {
public:
    // A place for things we don't want visible here.
    class Native;
    friend class Native;

    /* General stuff (valid for query or update) ****************************/
    // @param cfp Configuration: we make a local copy.
    Db(const RclConfig *cfp);
    ~Db();
    Db(const Db&) = delete;
    Db& operator=(const Db&) = delete;

    enum OpenMode {DbRO, DbUpd, DbTrunc};
    enum OpenFlags {DbOFNone=0, DbOFNoTmpDb=0x1};
    bool isWriteMode(OpenMode mode) {
        return mode == DbUpd || mode == DbTrunc;
    }
    enum OpenError {DbOpenNoError, DbOpenMainDb, DbOpenExtraDb};
    bool open(OpenMode mode, OpenError *error = nullptr, int flags = 0);
    bool close();
    bool isopen();

    /** Get explanation about last error */
    std::string getReason() const {return m_reason;}

    /** Return all possible stemmer names */
    static std::vector<std::string> getStemmerNames();

    /** Return existing stemming databases */
    std::vector<std::string> getStemLangs();

    /** Check if index stores the documents' texts. Only valid after open */
    bool storesDocText();
    
    /** Test word for spelling correction candidate: not too long, no special chars... 
     * @param with_aspell test for use with aspell, else for xapian speller */
    static bool isSpellingCandidate(const std::string& term, bool with_aspell=true);

    /** Return spelling suggestion */
    bool getSpellingSuggestions(const std::string& word, std::vector<std::string>& suggs);

    /* The next two, only for searchdata, should be somehow hidden */
    /* Return configured stop words */
    const StopList& getStopList() const {return *m_stops;}
    /* Field name to prefix translation (ie: author -> 'A') */
    bool fieldToTraits(const std::string& fldname, const FieldTraits **ftpp, bool isquery = false);

    /* Update-related methods ******************************************/

    /** Test if the db entry for the given udi is up to date.
     *
     * This is done by comparing the input and stored sigs. This is
     * used both when indexing and querying (before opening a document 
     * using stale info).
     *
     * **This assumes that the udi pertains to the main index (idxi==0).**
     *
     * Side-effect when the db is writeable and the document up to
     * date: set the existence flag for the file document and all
     * subdocs if any (for later use by 'purge()')
     *
     * @param udi Unique Document Identifier (as chosen by indexer).
     * @param sig New signature (as computed by indexer).
     * @param xdocid[output] Non-zero if doc existed. Should be considered 
     *    as opaque, to be used for a possible later call to setExistingFlags()
     *    Note that if inplaceReset is set, the return value is non-zero but not
     *    an actual docid, it's only used as a flag in this case.
     * @param osig[output] old signature.
     */
    bool needUpdate(const std::string &udi, const std::string& sig, 
                    unsigned int *xdocid = nullptr, std::string *osig = nullptr);

    /**
     * Unset the existence bits for the documents from a specific backend, and set them for all the
     * others. This must be called before indexing the backend, so that purge() can be called after
     * indexing and only affect the documents for the specified backend.
     *
     * @param backend the backend name (e.g. "FS", "BGL", ...)
     */
    bool preparePurge(const std::string& backend);
    
    /** Set the existence flags for the document and its eventual subdocuments
     * 
     * This can be called by the indexer after needUpdate() has returned true,
     * if the indexer does not wish to actually re-index (e.g.: the doc is 
     * known to cause errors).
     */
    void setExistingFlags(const std::string& udi, unsigned int docid);

    /** Indicate if we are doing a systematic reindex. This complements
        needUpdate() return */
    bool inFullReset() {return m_inPlaceReset || m_mode == DbTrunc;}

    /** Add or update document identified by unique identifier.
     * @param config Config object to use. Can be the same as the member config
     *   or a clone, to avoid sharing when called in multithread context.
     * @param udi the Unique Document Identifier is opaque to us. 
     *   Maximum size 150 bytes.
     * @param parent_udi the UDI for the container document. In case of complex
     *  embedding, this is not always the immediate parent but the UDI for
     *  the container file (which may be a farther ancestor). It is
     *  used for purging subdocuments when a file ceases to exist and
     *  to set the existence flags of all subdocuments of a container
     *  that is found to be up to date. In other words, the
     *  parent_udi is the UDI for the ancestor of the document which
     *  is subject to needUpdate() and physical existence tests (some
     *  kind of file equivalent). Empty for top-level docs. Should
     *  probably be renamed container_udi.
     * @param doc container for document data. Should have been filled as 
     *   much as possible depending on the document type. 
     *   ** doc will be modified in a destructive way **
     */
    bool addOrUpdate(const std::string &udi, const std::string &parent_udi, Doc &doc);

#ifdef IDX_THREADS
    void closeQueue();
    void waitUpdIdle();
#endif

    /** Delete document(s) for given UDI, including subdocs */
    bool purgeFile(const std::string &udi, bool *existed = nullptr);
    /** Delete subdocs with an out of date sig. We do this to purge
        obsolete subdocs during a partial update where no general purge
        will be done */
    bool purgeOrphans(const std::string &udi);

    /** Remove documents that no longer exist in the file system. This
     * depends on the update map, which is built during
     * indexing (needUpdate() / addOrUpdate()). 
     *
     * This should only be called after a full walk of
     * the file system, else the update map will not be complete, and
     * many documents will be deleted that shouldn't, which is why this
     * has to be called externally, rcldb can't know if the indexing
     * pass was complete or partial.
     */
    bool purge();

    /** Create stem expansion database for given languages. */
    bool createStemDbs(const std::vector<std::string> &langs);
    /** Delete stem expansion database for given language. */
    bool deleteStemDb(const std::string &lang);

    /* Query-related methods ************************************/

    /** Return total docs in db */
    int  docCnt(); 
    /** Return count of docs which have an occurrence of term */
    int termDocCnt(const std::string& term);
    /** Add extra Xapian database for querying. 
     * @param dir must point to something which can be passed as parameter 
     *      to a Xapian::Database constructor (directory or stub).
     */
    bool addQueryDb(const std::string &dir);
    /** Remove extra database. if dir == "", remove all. */
    bool rmQueryDb(const std::string &dir);
    /** Set the extra indexes to the input list. */
    bool setExtraQueryDbs(const std::vector<std::string>& dbs);

    /** Check if document comes from the main index (this is used to
        decide if we can update the index for it */
    bool fromMainIndex(const Doc& doc);

    /** Retrieve the stored doc text. This returns false if the index does not
        store raw text or other problems (discriminate with storesDocText(). 
        On success, the data is stored in doc.text
    */
    bool getDocRawText(Doc& doc);
    
    /** Retrieve an index designator for the document result. This is used 
     * by the GUI document history feature for remembering where a
     * doc comes from and allowing later retrieval (if the ext index
     * is still active...).
     */
    std::string whatIndexForResultDoc(const Doc& doc);
    
    /** Tell if directory seems to hold xapian db */
    static bool testDbDir(const std::string &dir, bool *stripped = nullptr);

    /** Return the index terms that match the input string
     * Expansion is performed either with either wildcard or regexp processing
     * Stem expansion is performed if lang is not empty 
     * 
     * @param typ_sens defines the kind of expansion: none, wildcard, 
     *    regexp or stemming. "none" may still expand case,
     *    diacritics and synonyms, depending on the casesens, diacsens and 
     *    synexp flags.
     * @param lang sets the stemming language(s). Can be a space-separated list
     * @param term is the term to expand
     * @param result is the main output
     * @param max defines the maximum result count
     * @param field if set, defines the field within with the expansion should
     *        be performed. Only used for wildcards and regexps, stemming is
     *        always global. If this is set, the resulting output terms 
     *        will be appropriately prefixed and the prefix value will be set 
     *        in the TermMatchResult header
     */
    enum MatchType {ET_NONE=0, ET_WILD=1, ET_REGEXP=2, ET_STEM=3, 
        ET_DIACSENS=8, ET_CASESENS=16, ET_SYNEXP=32, ET_PATHELT=64};
    int matchTypeTp(int tp) {
        return tp & 7;
    }
    bool termMatch(int typ_sens, const std::string &lang, const std::string &term,
                   TermMatchResult& result, int max = -1, const std::string& field = "",
                   std::vector<std::string> *multiwords = nullptr);
    bool dbStats(DbStats& stats, bool listFailed);
    /** Return min and max years for doc mod times in db */
    bool maxYearSpan(int *minyear, int *maxyear);
    /** Return all mime types in index. This can be different from the
        ones defined in the config because of 'file' command
        usage. Inserts the types at the end of the parameter */
    bool getAllDbMimeTypes(std::vector<std::string>&);

    /** Compute a list of all the directories containing indexed documents, down to a given depth

        @param depth depth belowr a possible computed common prefix, that is, if all
          directories are relative to /home/you, a depth of 2 would get you /home/you/1/2 but 
          not /home/you/1/2/3
        @param[out] commonprefix common prefix path for the list. May be "/".
        @param[out] dirs the computed list (full paths including the prefix).
    */
    bool dirlist(int depth, std::string& commonprefix, std::vector<std::string>& dirs);

    /** Wildcard expansion specific to file names. Internal/sdata use only */
    bool filenameWildExp(const std::string& exp, std::vector<std::string>& names, int max);

    /** Set parameters for synthetic abstract generation */
    void setAbstractParams(int idxTrunc, int synthLen, int syntCtxLen);
    int getAbsCtxLen() const {
        return m_synthAbsWordCtxLen;
    }
    int getAbsLen() const {
        return m_synthAbsLen;
    }

    /** Decide if we expand queries to more common terms which spell almost like the user term */
    void setUseSpellFuzz(bool onoff) {
        m_usingSpellFuzz = onoff;
    }
    /** Set maximum spelling distance when considering terms for spelling expansion */
    void setMaxSpellDist(int max) {
        m_maxSpellDistance = max;
    }
    int getMaxSpellDist() {
        return m_maxSpellDistance;
    }

    /** Get document for given udi and db index
     *
     * Used to retrieve ancestor documents.
     * @param udi The unique document identifier.
     * @param idxdoc A document from the same database as an opaque way to pass
     *   the database id (e.g.: when looking for parent in a multi-database 
     *   context).
     * @param[out] doc The output Recoll document.
     * @return True for success.
     */
    bool getDoc(const std::string &udi, const Doc& idxdoc, Doc &doc);

    /** Get document for given udi and index directory. 
     *
     * Used by the 'history' feature. This supposes that the extra db is still active.
     * @param udi The unique document identifier.
     * @param dbdir The index directory, from storage, as returned by 
     *   whatIndexForResultDoc() at the time of the query. Can be
     *   empty to mean "main index" (allows the history to avoid
     *   storing the main dbdir value).
     * @param[out] doc The output Recoll document.
     * @return True for success.
     */
    bool getDoc(const std::string &udi, const std::string& dbdir, Doc &doc, bool fetchtext=false);

    /** Same as from dbdir but use index integer index (main==0). Mostly for the python module */
    bool getDoc(const std::string& udi, int idxi, Doc& doc, bool fetchtext=false);

    /** Retrieve the UDI for a query result document. We do this lazily: it's not always
     *  needed and it takes about 20% of the document fetch time because of the need to
     *  access the postlist. This both returns the UDI and sets it in the meta array. */
    std::string fetchUdi(Doc& doc);
        
    /** Test if documents has sub-documents. 
     *
     * This can always be detected for file-level documents, using the
     * postlist for the parent term constructed with udi.
     *
     * For non file-level documents (e.g.: does an email inside an
     * mbox have attachments ?), detection is dependant on the filter
     * having set an appropriate flag at index time. Higher level code
     * can't detect it because the doc for the parent may have been
     * seen before any children. The flag is stored as a value in the
     * index.
     */
    bool hasSubDocs(Doc &idoc);

    /** Get subdocuments of given document. 
     *
     * For file-level documents, these are all docs indexed by the
     * parent term built on idoc.udi. For embedded documents, the
     * parent doc is looked for, then its subdocs list is 
     * filtered using the idoc ipath as a prefix.
     */
    bool getSubDocs(Doc& idoc, std::vector<Doc>& subdocs);

    /** Get container (top level file) document. 
     *
     * If the input is not a subdocument, this returns a copy of the input.
     */
    bool getContainerDoc(Doc &idoc, Doc& ctdoc);
    
    /** Get duplicates (md5) of document */
    bool docDups(const Doc& idoc, std::vector<Doc>& odocs);

    /* The following are mainly for the aspell module */
    /** Whole term list walking. */
    TermIter *termWalkOpen();
    bool termWalkNext(TermIter *, std::string &term);
    void termWalkClose(TermIter *);
    /** Test term existence */
    bool termExists(const std::string& term);
    /** Test if terms stem to different roots. */
    bool stemDiffers(const std::string& lang, const std::string& term, const std::string& base);

    const RclConfig *getConf() {return m_config;}

    /** 
     * Activate the "in place reset" mode where all documents are
     * considered as needing update. It should be set at the start of
     * the indexing pass. 
     */
    void setInPlaceReset() {m_inPlaceReset = true;}

    /** Flush interval get/set. This is used by the first indexing
        pass to override the config value and flush more rapidly
        initially so that the user can quickly play with queries */
    int getFlushMb() {
        return  m_flushMb;
    }
    void setFlushMb(int mb) {
        m_flushMb = mb;
    }
    bool doFlush();

    // Read and store a synonyms groups file. Use empty fn to reset. Different uses at query
    // and index times. See the comments for m_syngroups for a detailed explanation.
    bool setSynGroupsFile(const std::string& fn);
    const SynGroups& getSynGroups() {return *m_syngroups;}
    
    // Mark all documents with an UDI having @param udi as prefix as
    // existing. Only works if the UDIs for the store are
    // hierarchical of course.  Used by FsIndexer to avoid purging
    // files for a topdir which is on a removable file system and
    // currently unmounted (topdir does not exist or is empty.
    bool udiTreeMarkExisting(const std::string& udi);

    /* This has to be public for access by embedded Query::Native */
    Native *m_ndb{nullptr};
    
private:
    const RclConfig *m_config;
    std::string     m_reason; // Error explanation

    // Xapian directories for additional databases to query
    std::vector<std::string> m_extraDbs;
    OpenMode m_mode{Db::DbRO};
    // File existence vector: this is filled during the indexing pass. Any
    // document whose bit is not set at the end is purged
    std::vector<bool> updated;
    // Text bytes indexed since beginning
    long long    m_curtxtsz{0};
    // Text bytes at last flush
    long long    m_flushtxtsz{0};
    // Text bytes at last fsoccup check
    long long    m_occtxtsz{0};
    // First fs occup check ?
    int         m_occFirstCheck{1};

    // Synonym groups. This has two different uses, at query or indexing time. The main use is at
    // query time.
    //  - Query time: this is set by the upper level query program (GUI or recollq, not accessible
    //    from Python at the moment for no special reason). The synonym file name comes from
    //    whatever upper level pref. It is used during query expansion to OR the synonym terms.
    //    There is no strict reason that this has to be an Rcl::Db member, as it is only used when
    //    building each query. It could be a SearchData member, or even a parameter to
    //    Query::setQuery(). Otoh, building the syngroups structure from a file may be expensive and
    //    it's unlikely to change with every query, so it makes sense to cache it, and Rcl::Db is
    //    not a bad place for this.
    // - Index time: the data comes from the idxsynonyms parameter which has no default value. It is
    //   ONLY used for generating multiword terms to allow phrase/proximity searches to work with
    //   multiword synonyms. Ex.: if we have an (applejack "apple jack") synonym group, without
    //   idxsynonyms, if "apple jack" is found in a text the indexer will issue two terms at
    //   positions x and x+1 so that a search for the "apple jack" synonym at position x will
    //   fail. If idxsynonyms is set, the indexer will also issue a multiword "apple jack" term at
    //   position x so that phrase/prox searches will work. Another approach would have been to have
    //   a "phrase within phrase" at query time, but this is not supported by Xapian.
    std::unique_ptr<SynGroups> m_syngroups;

    // Aspell object if needed
    Aspell *m_aspell{nullptr};

    /***************
     * Parameters cached out of the configuration files. Logically const 
     * after init */
    // Stop terms: those don't get indexed.
    std::unique_ptr<StopList> m_stops;
    // Truncation length for stored meta fields
    int         m_idxMetaStoredLen{150};
    // This is how long an abstract we keep or build from beginning of
    // text when indexing. It only has an influence on the size of the
    // db as we are free to shorten it again when displaying
    int          m_idxAbsTruncLen{250};
    // Document text truncation length
    int          m_idxTextTruncateLen{0};
    // This is the size of the abstract that we synthetize out of query
    // term contexts at *query time*
    int          m_synthAbsLen{250};
    // This is how many words (context size) we keep around query terms
    // when building the abstract
    int          m_synthAbsWordCtxLen{4};
    // Flush threshold. Megabytes of text indexed before we flush.
    int          m_flushMb{-1};
    // Maximum file system occupation percentage
    int          m_maxFsOccupPc{0};
    // Limit Xapian stored object sizes. Note that these are last ditch efforts to prevent a hard
    // Xapian error, and are partly redundant with other limits in the doc preparation pipeline.
    // The hard Xapian limit for this is roughly of the order of 100 MB, maybe depending on version,
    // largely over what we may actually want to store. The values can be changed in the config.
    int          m_maxdbdatarecordkbs{1000}; // 1MB
    int          m_maxdbdstoredtextmbs{50};  // 50MB
    // Using spelling approximation?
    bool m_usingSpellFuzz{true};
    // Maximum dam-lev distance when considering terms for spelling fuzz
    int m_maxSpellDistance{1};
    int m_autoSpellRarityThreshold{200000};
    int m_autoSpellSelectionThreshold{20};
    
    // Database directory
    std::string       m_basedir;
    // When this is set, all documents are considered as needing a reindex.
    // This implements an alternative to just erasing the index before 
    // beginning, with the advantage that, for small index formats updates, 
    // between releases the index remains available while being recreated.
    bool m_inPlaceReset{false};
    static bool o_nospell_chars[256];
    /******* End logical constnesss */

#ifdef IDX_THREADS
    friend void *DbUpdWorker(void*);
#endif // IDX_THREADS

    // Internal form of setExistingFlags: no locking
    void i_setExistingFlags(const std::string& udi, unsigned int docid);
    // Reinitialize when adding/removing additional dbs
    bool adjustdbs();
    // Match the input term (which must be in index form, diacase stripped as needed) and actual
    // index contents, possibly using wildcard or regexp matching. If typ_sens is ET_NONE, this is
    // just an index lookup. Accumulate the results in the TermMatchResult mutable input.
    bool idxTermMatch(int typ_sens, const std::string &term, TermMatchResult& result,
                      int max = -1, const std::string& field = std::string());

    // Flush when idxflushmb is reached
    bool maybeflush(int64_t moretext);
    bool docExists(const std::string& uniterm);

    void spellExpand(const std::string& term, const std::string& field,
                     std::vector<std::string>& expansion);
  
    // At the end of an indexing using multiple output Xapian indexes: compact the whole and replace
    // current index. Everything must be committed and idle. Throws Xapian exception in case of
    // error. This can only be called by close() and it deletes m_ndb.
    void mergeAndCompact();
};

// This has to go somewhere, and as it needs the Xapian version, this is
// the most reasonable place.
std::string version_string();

}

#endif /* _DB_H_INCLUDED_ */
