package com.tt.honeyDue.sharing

import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.models.HoneyDueShareCodec
import com.tt.honeyDue.models.Contractor
import com.tt.honeyDue.network.APILayer
import com.tt.honeyDue.network.ApiResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

/**
 * Manages contractor export and import via .honeydue files on Android.
 */
object ContractorSharingManager {

    /**
     * Creates a share Intent for a contractor.
     * The contractor data is written to a temporary .honeydue file and shared via FileProvider.
     *
     * @param context Android context
     * @param contractor The contractor to share
     * @return Share Intent or null if creation failed
     */
    fun createShareIntent(context: Context, contractor: Contractor): Intent? {
        return try {
            val currentUsername = DataManager.currentUser.value?.username ?: "Unknown"
            val jsonString = HoneyDueShareCodec.encodeContractorPackage(contractor, currentUsername)
            val fileName = HoneyDueShareCodec.safeShareFileName(contractor.name)

            // Create shared directory
            val shareDir = File(context.cacheDir, "shared")
            shareDir.mkdirs()

            val file = File(shareDir, fileName)
            file.writeText(jsonString)

            val uri = FileProvider.getUriForFile(
                context,
                "${context.packageName}.fileprovider",
                file
            )

            Intent(Intent.ACTION_SEND).apply {
                type = "application/json"
                putExtra(Intent.EXTRA_STREAM, uri)
                putExtra(Intent.EXTRA_SUBJECT, "Contractor: ${contractor.name}")
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * Imports a contractor from a content URI.
     *
     * @param context Android context
     * @param uri The content URI of the .honeydue file
     * @return ApiResult with the created Contractor on success, or error on failure
     */
    suspend fun importContractor(context: Context, uri: Uri): ApiResult<Contractor> {
        return withContext(Dispatchers.IO) {
            try {
                // Check authentication
                if (DataManager.authToken.value == null) {
                    return@withContext ApiResult.Error("You must be logged in to import a contractor", 401)
                }

                // Read file content
                val inputStream = context.contentResolver.openInputStream(uri)
                    ?: return@withContext ApiResult.Error("Could not open file")

                val jsonString = inputStream.bufferedReader().use { it.readText() }
                inputStream.close()

                val createRequest = HoneyDueShareCodec.createContractorImportRequestOrNull(
                    jsonContent = jsonString,
                    availableSpecialties = DataManager.contractorSpecialties.value
                ) ?: return@withContext ApiResult.Error("Invalid contractor share package")

                // Call API
                APILayer.createContractor(createRequest)
            } catch (e: Exception) {
                e.printStackTrace()
                ApiResult.Error("Failed to import contractor: ${e.message}")
            }
        }
    }

    /**
     * Checks if the given URI appears to be a .honeydue file.
     */
    fun ishoneyDueFile(context: Context, uri: Uri): Boolean {
        // Check file extension from URI path
        val path = uri.path ?: uri.toString()
        if (path.endsWith(".honeydue", ignoreCase = true)) {
            return true
        }

        // Try to get display name from content resolver
        try {
            context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
                    if (nameIndex >= 0) {
                        val name = cursor.getString(nameIndex)
                        if (name?.endsWith(".honeydue", ignoreCase = true) == true) {
                            return true
                        }
                    }
                }
            }
        } catch (e: Exception) {
            // Ignore errors, fall through to false
        }

        return false
    }
}
