package com.tt.honeyDue.network

import io.ktor.client.*
import io.ktor.client.engine.darwin.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
import platform.Foundation.NSLocale
import platform.Foundation.NSTimeZone
import platform.Foundation.localTimeZone
import platform.Foundation.preferredLanguages

actual fun getLocalhostAddress(): String = "127.0.0.1"

actual fun getDeviceLanguage(): String {
    val preferredLanguages = NSLocale.preferredLanguages
    val firstLanguage = preferredLanguages.firstOrNull() as? String
    // Extract just the language code (e.g., "en" from "en-US")
    return firstLanguage?.split("-")?.firstOrNull() ?: "en"
}

actual fun getDeviceTimezone(): String {
    return NSTimeZone.localTimeZone.name
}

actual fun createHttpClient(): HttpClient {
    return HttpClient(Darwin) {
        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true
                isLenient = true
                prettyPrint = true
            })
        }

        install(Logging) {
            logger = Logger.DEFAULT
            // Only log full request/response bodies in local dev to avoid
            // leaking auth tokens and PII in production logs.
            level = if (ApiConfig.CURRENT_ENV == ApiConfig.Environment.LOCAL) LogLevel.ALL else LogLevel.INFO
        }

        install(DefaultRequest) {
            headers.append("Accept-Language", getDeviceLanguage())
            headers.append("X-Timezone", getDeviceTimezone())
        }

        engine {
            configureRequest {
                setAllowsCellularAccess(true)
            }
        }

        // Shared plugins: gzip, retry with backoff, timeouts, token refresh
        installCommonPlugins()
    }
}
