//
//  SessionStats.swift
//  Confab
//
//  Session statistics tracking
//
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
// Copyright (C) 2026 Rune Olsen
//
// This file is part of Confab.
//
// Confab is licensed under the PolyForm Noncommercial License 1.0.0.
// You may use, study, modify, and share it for any noncommercial
// purpose. Commercial use — including selling Confab or any part of
// it, standalone or bundled into another product or service —
// requires a separate commercial license from the copyright holder.
//
// See the LICENSE file or
// <https://polyformproject.org/licenses/noncommercial/1.0.0> for
// the full license text. For commercial licensing, contact Rune
// Olsen via <https://confab.no>.


import Foundation

struct SessionStats {
    var totalInputTokens: Int = 0
    var totalOutputTokens: Int = 0
    var totalCost: Double = 0.0
    var messageCount: Int = 0
    var hasCostData: Bool = false
    
    var totalTokens: Int {
        totalInputTokens + totalOutputTokens
    }
    
    var totalTokensDisplay: String {
        if totalTokens >= 1_000_000 {
            return String(format: "%.1fM", Double(totalTokens) / 1_000_000)
        } else if totalTokens >= 1000 {
            return String(format: "%.1fK", Double(totalTokens) / 1000)
        } else {
            return "\(totalTokens)"
        }
    }
    
    var totalCostDisplay: String {
        hasCostData ? String(format: "$%.4f", totalCost) : "N/A"
    }

    var averageCostPerMessage: Double {
        guard messageCount > 0 else { return 0.0 }
        return totalCost / Double(messageCount)
    }

    var averageCostDisplay: String {
        hasCostData ? String(format: "$%.4f", averageCostPerMessage) : "N/A"
    }

    mutating func addMessage(inputTokens: Int?, outputTokens: Int?, cost: Double?) {
        if let input = inputTokens {
            totalInputTokens += input
        }
        if let output = outputTokens {
            totalOutputTokens += output
        }
        if let messageCost = cost {
            totalCost += messageCost
            hasCostData = true
        }
        messageCount += 1
    }

    mutating func reset() {
        totalInputTokens = 0
        totalOutputTokens = 0
        totalCost = 0.0
        messageCount = 0
        hasCostData = false
    }
}
