#include <iostream>
#include <string>
#include <curl/curl.h>
#include <json/json.h>

using namespace std;

// تابع برای پردازش پاسخ دریافتی از API
size_t WriteCallback(void* contents, size_t size, size_t nmemb, string* output) {
    size_t totalSize = size * nmemb;
    output->append((char*)contents, totalSize);
    return totalSize;
}

int main() {
    string cityName;
    cout << "Enter the city name: ";
    getline(cin, cityName);

    // API Key و URL پایه برای درخواست به OpenWeatherMap
    string apiKey = "YOUR_API_KEY"; // اینجا API Key خود را وارد کنید
    string url = "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&appid=" + apiKey + "&units=metric";

    CURL* curl;
    CURLcode res;
    string readBuffer;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        // ارسال درخواست
        res = curl_easy_perform(curl);

        // بررسی اینکه درخواست موفقیت‌آمیز بوده است یا نه
        if (res != CURLE_OK) {
            cerr << "Request failed: " << curl_easy_strerror(res) << endl;
        } else {
            // پردازش پاسخ JSON
            Json::Value jsonData;
            Json::CharReaderBuilder reader;
            string errs;
            istringstream ss(readBuffer);
            if (Json::parseFromStream(reader, ss, &jsonData, &errs)) {
                // نمایش اطلاعات آب و هوا
                cout << "Weather Information for " << cityName << ":" << endl;
                cout << "Temperature: " << jsonData["main"]["temp"].asFloat() << "°C" << endl;
                cout << "Weather: " << jsonData["weather"][0]["description"].asString() << endl;
                cout << "Humidity: " << jsonData["main"]["humidity"].asInt() << "%" << endl;
                cout << "Wind Speed: " << jsonData["wind"]["speed"].asFloat() << " m/s" << endl;
            } else {
                cerr << "Error parsing JSON response." << endl;
            }
        }

        // تمیز کردن
        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();
    return 0;
}