import SwiftData
import Foundation

@Model
final class DailyLog {
    var id: String = ""
    var dateString: String = ""
    var reviewCount: Int = 0
    var correctCount: Int = 0
    var studySeconds: Int = 0

    var accuracy: Double {
        guard reviewCount > 0 else { return 0 }
        return Double(correctCount) / Double(reviewCount)
    }

    init(dateString: String, reviewCount: Int = 0, correctCount: Int = 0) {
        self.id = Self.makeID(dateString)
        self.dateString = dateString
        self.reviewCount = reviewCount
        self.correctCount = correctCount
    }

    static func makeID(_ dateString: String) -> String {
        dateString
    }

    func refreshIdentityIfNeeded() {
        let expected = Self.makeID(dateString)
        if id != expected {
            id = expected
        }
    }

    /// Defensive formatter: explicit POSIX locale + current timezone so date
    /// strings can never drift due to locale formatting (e.g. Arabic numerals)
    /// or implicit-zone shifts. The string format is timezone-naive
    /// `yyyy-MM-dd`, which works because we only ever compare to other
    /// strings produced by this same formatter.
    private static func makeFormatter() -> DateFormatter {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = .current
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }

    static func dateString(from date: Date) -> String {
        makeFormatter().string(from: date)
    }

    static func todayString() -> String {
        dateString(from: Date())
    }

    static func date(from string: String) -> Date? {
        makeFormatter().date(from: string)
    }
}
