import Foundation

final class HistoryManager {

    private var fm: FileManager {
        .default
    }

    var documentDirectory: URL {
        try! fm.url(
        for: .documentDirectory,
        in: .userDomainMask,
        appropriateFor: nil, create: true)
    }

    private var fileUrl: URL {
        documentDirectory.appendingPathComponent("history.bin")
    }

    func loadEntries() -> [HistoryItem] {
        let url = fileUrl
        guard fm.fileExists(atPath: url.path) else {
            print("No history data found")
            return []
        }
        let content: Data
        do {
            content = try Data(contentsOf: url)
        } catch {
            print("Failed to read history data: \(error)")
            return []
        }
        var index = 0
        var entries = [HistoryItem]()
        while index < content.count {
            guard let entry = HistoryItem(decodeFrom: content, index: &index) else {
                print("Failed to read entry at index \(index)")
                return entries
            }
            entries.append(entry)
        }
        return entries.sorted().reversed()
    }

    func save(item: HistoryItem) throws {
        let url = fileUrl
        let data = item.encoded
        guard fm.fileExists(atPath: url.path) else {
            try data.write(to: url)
            print("First history item written")
            return
        }
        let handle = try FileHandle(forWritingTo: url)
        try handle.seekToEnd()
        try handle.write(contentsOf: data)
        try handle.close()
        print("History item written")
    }
}
