import Foundation

/// Utility helper to resolve dynamic iOS App Sandbox document paths for audio files
/// and convert between absolute and relative paths.
public struct AudioPathHelper {
    /// Resolves an audio file path (which could be nil, a relative filename, or an outdated absolute sandbox path from a prior app launch)
    /// to a valid, existing URL in the current app container's Documents directory.
    public static func resolveURL(for path: String?) -> URL? {
        guard let path = path, !path.isEmpty else { return nil }
        
        let fm = FileManager.default
        
        // 1. Direct check: If path exists as-is, return it
        if fm.fileExists(atPath: path) {
            return URL(fileURLWithPath: path)
        }
        
        // 2. Dynamic Sandbox check: Extract filename and search in current Documents directory
        let filename = (path as NSString).lastPathComponent
        guard !filename.isEmpty else { return nil }
        
        if let documentsURL = fm.urls(for: .documentDirectory, in: .userDomainMask).first {
            let candidateURL = documentsURL.appendingPathComponent(filename)
            if fm.fileExists(atPath: candidateURL.path) {
                return candidateURL
            }
        }
        
        return nil
    }
    
    /// Converts an absolute or relative file path into a relative filename (e.g. "merged_123.m4a") suitable for persistent storage.
    public static func relativePath(from pathOrURL: String?) -> String? {
        guard let pathOrURL = pathOrURL, !pathOrURL.isEmpty else { return nil }
        return (pathOrURL as NSString).lastPathComponent
    }
}
