#include "tskv_helpers.h"

#include <util/string/cast.h>
#include <util/string/split.h>

void TskvConvertKiwiLegacy(NUtil::TTSKVRecord& res, const TStringBuf& kiwiMsg) {
    // Parse legacy key-value error string
    // i.e. "TCookieWriter: kiwi write error key# http://www.lyricscatch.com/ expl# FORBIDDEN source"
    TStringStream expl;
    TStringBuf key, nextKey;
    for(const auto& it : StringSplitter(kiwiMsg).Split('#')) {
        const TStringBuf& segment = it.Token();
        TStringBuf value;

        if (!it.Delim().empty()) { // if not last
            size_t p = segment.rfind(' ');
            if (p == TStringBuf::npos) {
                nextKey = segment;
                value = TStringBuf();
            } else {
                nextKey = TStringBuf(segment.cbegin() + p + 1, segment.cend());
                value = TStringBuf(segment.cbegin(), segment.cbegin() + p);
            }
        } else {
            value = segment;
        }

        if (key && key != "expl")
            res.ForceAdd(ToString(key), StripString(value));
        else if (value) {
            if (expl)
                expl << ' ';
            expl << StripString(value);
        }

        key = nextKey;
    }

    if (expl)
        res.Add("expl", expl.Str());
}
