import Foundation

// MARK: - String Extensions
extension String {
    var trimmed: String {
        trimmingCharacters(in: .whitespaces)
    }

    /// Fast attribute extraction without regex - looks for `attributeName="value"`
    /// This is ~5-10x faster than regex-based extraction
    func extractAttribute(_ attributeName: String) -> String? {
        // Look for attributeName="
        let searchPattern = attributeName + "=\""
        guard let startRange = self.range(of: searchPattern) else {
            return nil
        }

        // Find the closing quote
        let valueStart = startRange.upperBound
        guard let endRange = self.range(of: "\"", range: valueStart..<self.endIndex) else {
            return nil
        }

        return String(self[valueStart..<endRange.lowerBound])
    }

    func extractAfterComma() -> String? {
        guard let commaIndex = lastIndex(of: ",") else { return nil }
        let startIndex = index(after: commaIndex)
        return String(self[startIndex...]).trimmed
    }
}

// MARK: - URL Extensions
extension URL {
    func appendingXStreamParameters(username: String, password: String, type: String = "m3u_plus", output: String = "ts") -> URL? {
        var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
        components?.queryItems = [
            URLQueryItem(name: "username", value: username),
            URLQueryItem(name: "password", value: password),
            URLQueryItem(name: "type", value: type),
            URLQueryItem(name: "output", value: output)
        ]
        return components?.url
    }
}

// MARK: - Data Extensions
extension Data {
    var utf8String: String? {
        String(data: self, encoding: .utf8)
    }
}

// MARK: - Error Extensions
extension Error {
    var isNetworkError: Bool {
        if let urlError = self as? URLError {
            return urlError.code == .notConnectedToInternet ||
                   urlError.code == .networkConnectionLost ||
                   urlError.code == .dataNotAllowed
        }
        return false
    }

    var isTimeoutError: Bool {
        if let urlError = self as? URLError {
            return urlError.code == .timedOut
        }
        return false
    }
}
