// macOS bundle metadata: thin endpoint surface so CxWebApp can advertise the
// SwiftPM `apps/cxai-mac` app (build info + download link) without needing the
// actual .app to live inside this image.
//
// Configure with:
//   CXAI_MAC_BUILD_INFO   path to a build-info.json (default /opt/cxwebapp/share/cxai-mac/build-info.json)
//   CXAI_MAC_DOWNLOAD_URL public URL to the .app.zip (returned in /api/mac/info)

#include "crow.h"
#include "routes.h"

#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>

namespace routes {

namespace {

std::string slurp(const std::string& path) {
    std::ifstream ifs(path, std::ios::binary);
    if (!ifs.is_open()) return "";
    std::ostringstream ss;
    ss << ifs.rdbuf();
    return ss.str();
}

std::string env_or(const char* k, const char* fallback) {
    if (const char* v = std::getenv(k)) return std::string(v);
    return std::string(fallback);
}

} // anonymous namespace

void register_mac(crow::SimpleApp& app) {

    CROW_ROUTE(app, "/api/mac/healthz")
    ([]() {
        crow::json::wvalue r;
        r["ok"] = true;
        r["service"] = "cxai-mac";
        return r;
    });

    CROW_ROUTE(app, "/api/mac/info")
    ([]() {
        const std::string path = env_or(
            "CXAI_MAC_BUILD_INFO",
            "/opt/cxwebapp/share/cxai-mac/build-info.json");
        std::string body = slurp(path);
        crow::json::wvalue r;
        if (body.empty()) {
            r["error"] = "build_info_unavailable";
            r["path"]  = path;
            auto resp = crow::response(404, r);
            resp.add_header("Content-Type", "application/json");
            return resp;
        }
        // body is already JSON; pass through verbatim while still wrapping with
        // our envelope.
        auto loaded = crow::json::load(body);
        crow::json::wvalue info;
        if (loaded) {
            info = crow::json::wvalue(loaded);
        } else {
            info["raw"] = body;
        }
        crow::json::wvalue out;
        out["build"]        = std::move(info);
        out["download_url"] = env_or("CXAI_MAC_DOWNLOAD_URL", "");
        out["bundle_id"]    = env_or("CXAI_MAC_BUNDLE_ID", "com.cxai.cxai");
        auto resp = crow::response(200, out);
        resp.add_header("Content-Type", "application/json");
        return resp;
    });
}

} // namespace routes
