/*
 * Copyright (c) 2026 Meshtastic LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package org.meshtastic.feature.discovery.export

import org.koin.core.annotation.Single

private const val SEPARATOR_LENGTH = 60

@Single
class TextDiscoveryExporter : DiscoveryExporter {

    @Suppress("TooGenericExceptionCaught")
    override suspend fun export(data: DiscoveryExportData): ExportResult = try {
        val text = renderText(data)
        val fileName = DiscoveryReportFormatter.generateFileName(data.session, "txt")
        ExportResult.Success(content = text.encodeToByteArray(), mimeType = "text/plain", fileName = fileName)
    } catch (e: Exception) {
        ExportResult.Error("Text export failed: ${e.message}")
    }

    private fun renderText(data: DiscoveryExportData): String = buildString {
        appendLine("MESHTASTIC DISCOVERY REPORT")
        appendLine("=".repeat(SEPARATOR_LENGTH))
        appendLine()

        appendLine("SESSION OVERVIEW")
        appendLine("-".repeat(SEPARATOR_LENGTH))
        for ((label, value) in DiscoveryReportFormatter.formatSessionOverviewLines(data.session)) {
            appendLine("  $label: $value")
        }
        appendLine()

        for (result in data.presetResults) {
            appendLine("PRESET: ${result.presetName}")
            appendLine("-".repeat(SEPARATOR_LENGTH))
            for ((label, value) in DiscoveryReportFormatter.formatPresetLines(result)) {
                appendLine("  $label: $value")
            }

            val nodes = data.nodesByPreset[result.id].orEmpty()
            if (nodes.isNotEmpty()) {
                appendLine()
                appendLine("  Discovered Nodes (${nodes.size}):")
                for (node in nodes) {
                    appendLine("    ${DiscoveryReportFormatter.formatNodeLine(node)}")
                }
            }
            appendLine()
        }

        val summary = data.session.aiSummary
        if (!summary.isNullOrBlank()) {
            appendLine("AI ANALYSIS")
            appendLine("-".repeat(SEPARATOR_LENGTH))
            appendLine(summary)
            appendLine()
        }

        appendLine("=".repeat(SEPARATOR_LENGTH))
        appendLine("Generated by Meshtastic")
    }
}
