import Foundation

struct HealthExportDialogueTurn: Identifiable, Hashable, Sendable {
    enum Role: String, Sendable {
        case user
        case assistant

        var transcriptLabel: String {
            switch self {
            case .user: return String(appLoc: "我")
            case .assistant: return String(appLoc: "康康")
            }
        }
    }

    let id: UUID
    var role: Role
    var text: String
    var createdAt: Date

    init(role: Role, text: String, createdAt: Date = .now, id: UUID = UUID()) {
        self.id = id
        self.role = role
        self.text = text
        self.createdAt = createdAt
    }

    static func user(_ text: String) -> HealthExportDialogueTurn {
        HealthExportDialogueTurn(role: .user, text: text)
    }

    static func assistant(_ text: String) -> HealthExportDialogueTurn {
        HealthExportDialogueTurn(role: .assistant, text: text)
    }

    static func transcript(from turns: [HealthExportDialogueTurn]) -> String {
        turns
            .compactMap { turn -> String? in
                let cleaned = turn.text
                    .trimmingCharacters(in: .whitespacesAndNewlines)
                    .replacingOccurrences(of: "\n", with: " ")
                guard !cleaned.isEmpty else { return nil }
                return "\(turn.role.transcriptLabel): \(cleaned)"
            }
            .joined(separator: "\n")
    }
}
