import Foundation

enum SentenceBoundaryAPIError: LocalizedError {
    case invalidHash
    case hashMismatch

    var errorDescription: String? {
        switch self {
        case .invalidHash:
            return "video_hash 必须是 64 位 SHA-256 十六进制字符串"
        case .hashMismatch:
            return "服务端返回的句边界哈希与请求不一致"
        }
    }
}

enum SentenceBoundaryAPI {
    static func fetch(videoHash: String) async throws -> SentenceBoundaryDocument {
        let hash = videoHash.lowercased()
        guard hash.range(of: AppConfig.sha256Pattern, options: .regularExpression) != nil else {
            throw SentenceBoundaryAPIError.invalidHash
        }
        let result = try await HTTPClient.getJSON(
            SentenceBoundaryDocument.self,
            baseURL: AppConfig.serverBaseURL,
            path: "api/v1/videos/\(hash)/sentence-boundaries",
            timeout: AppConfig.readTimeout
        )
        guard result.value.videoHash.lowercased() == hash else {
            throw SentenceBoundaryAPIError.hashMismatch
        }
        return result.value
    }
}
