#include <balancer/kernel/cookie/gdpr/is_gdpr_b.h>
#include <balancer/kernel/cookie/gdpr/is_gdpr_b.pb.h>

#include <library/cpp/getopt/last_getopt.h>
#include <library/cpp/getopt/modchooser.h>
#include <library/cpp/string_utils/base64/base64.h>
#include <library/cpp/svnversion/svnversion.h>

#include <util/stream/output.h>

namespace NLastGetopt::NPrivate {
    template <>
    inline TInstant OptFromStringImpl<TInstant>(const TStringBuf& value) {
        if (ui32 t; TryFromString(value, t)) {
            return TInstant::Seconds(t);
        }
        return TInstant::ParseIso8601(value);
    }
}

class TMain: public TMainClassArgs {
    bool Verbose_ = false;
    NGdprCookie::TIsGdprB IsGdprB = {
        .BalancerVerHash=NGdprCookie::BalancerVerHash(),
        .Tstamp=Now(),
    };

protected:
    void RegisterOptions(NLastGetopt::TOpts& opts) override {
        opts.SetTitle("gen_is_gdpr_b -- generates is_gdpr_b cookie");
        opts.AddHelpOption('h');

        opts.AddCharOption('V').NoArgument().StoreValue(&Verbose_, true).Help("verbose");
        opts.AddLongOption("IsGdpr")
            .RequiredArgument("BOOL").StoreResultDef(&IsGdprB.IsGdpr).Help("current gdpr status");
        opts.AddLongOption("IsGdprNoVpn")
            .RequiredArgument("BOOL").StoreResult(&IsGdprB.IsGdprNoVpn).Help("last gdpr status outside vpn");
        opts.AddLongOption("Tstamp")
            .RequiredArgument("UNIT or yyyy-MM-ddThh:mm:ssZ").StoreResult(&IsGdprB.Tstamp).Help("timestamp");
        opts.AddLongOption("BalancerVerHash")
            .RequiredArgument("UINT").StoreResult(&IsGdprB.BalancerVerHash).Help("version hash");

        opts.SetFreeArgsMax(0);
    }

    int DoRun(NLastGetopt::TOptsParseResult&&) override {
        IsGdprB.Tstamp = TInstant::Hours(IsGdprB.Tstamp.Hours());
        if (Verbose_) {
            if (TStringBuf(GetTag())) {
                Cout << GetTag() << Endl;
            } else {
                Cout << GetBranch() << "@" << GetArcadiaLastChange() << Endl;
            }
            Cout << IsGdprB << Endl;
            NIsGdprB::TIsGdprB pb;
            Y_PROTOBUF_SUPPRESS_NODISCARD pb.ParseFromString(Base64Decode(IsGdprB.Render()));
            Cout << pb.ShortDebugString() << Endl;
        }
        Cout << IsGdprB.Render() << Endl;
        return 0;
    }
};

int main(int argc, const char** argv) {
    TMain().Run(argc, argv);
}
