import Foundation
import Darwin

public enum TransferKind: String, Codable {
    case copy, move, trash, delete
    /// Option+F5: comprime le sorgenti nell'archivio `destination`.
    case pack
    /// Option+F9: estrae gli archivi `sources` nella cartella `destination`.
    case extract

    public var verb: String {
        switch self {
        case .copy: return "Copia"
        case .move: return "Sposta"
        case .trash: return "Cestino"
        case .delete: return "Elimina"
        case .pack: return "Comprimi"
        case .extract: return "Estrai"
        }
    }
}

/// Cosa fare quando un file esiste già, per tutti i file da lì in avanti.
public enum ConflictPolicy: String, Codable, CaseIterable {
    case ask, overwriteAll, skipAll, overwriteOlder, overwriteSmaller, overwriteLarger, autoRename

    public var title: String {
        switch self {
        case .ask: return "Chiedi"
        case .overwriteAll: return "Sovrascrivi tutti"
        case .skipAll: return "Tralascia tutti"
        case .overwriteOlder: return "Sovrascrivi i più vecchi"
        case .overwriteSmaller: return "Sovrascrivi i più piccoli"
        case .overwriteLarger: return "Sovrascrivi i più grandi"
        case .autoRename: return "Rinomina automaticamente"
        }
    }
}

public struct TransferJob: Identifiable {
    public let id = UUID()
    public let kind: TransferKind
    public var sources: [URL]
    /// Cartella di destinazione (copia e sposta).
    public let destination: URL?
    /// Nuovo nome, solo con un elemento.
    public let newName: String?
    /// Maschera di rinomina come in TC ("*.*", "*.bak"), per più elementi.
    public let renamePattern: String?
    /// "Solo file di questo tipo".
    public let fileMask: String?
    public let verify: Bool
    public let policy: ConflictPolicy
    /// Per l'FTP: quali sorgenti remote sono cartelle e quanto pesano i file (dall'elenco del server).
    public var directorySources: Set<URL> = []
    public var sizes: [URL: Int64] = [:]
    /// Archivi: ogni archivio nella sua cartella (Option+F9), con i percorsi salvati, e
    /// "Sposta nell'archivio" (Option+F5: le sorgenti si cancellano dopo).
    public var extractToSubfolder = false
    public var withPaths = true
    public var deleteSources = false

    public init(kind: TransferKind, sources: [URL], destination: URL? = nil, newName: String? = nil,
                renamePattern: String? = nil, fileMask: String? = nil, verify: Bool = false, policy: ConflictPolicy = .ask) {
        self.kind = kind
        self.sources = sources
        self.destination = destination
        self.newName = sources.count == 1 ? newName : nil
        self.renamePattern = renamePattern
        let mask = fileMask?.trimmingCharacters(in: .whitespaces) ?? ""
        self.fileMask = mask.isEmpty || mask == "*.*" || mask == "*" ? nil : mask
        self.verify = verify
        self.policy = policy
    }

    public func targetName(for src: URL) -> String {
        if let newName { return newName }
        if let renamePattern { return NamePattern.apply(renamePattern, to: src.lastPathComponent) }
        return src.lastPathComponent
    }

    public var title: String {
        let what = sources.count == 1 ? "\"\(newName ?? sources[0].lastPathComponent)\"" : "\(sources.count) elementi"
        let dest = destination.map { Format.path($0) } ?? ""
        switch kind {
        case .copy: return "Copia di \(what) in \(dest)"
        case .move: return "Spostamento di \(what) in \(dest)"
        case .trash: return "Cestino: \(what)"
        case .delete: return "Eliminazione di \(what)"
        case .pack: return "Compressione di \(what) in \(dest)"
        case .extract: return "Estrazione di \(what) in \(dest)"
        }
    }
}

/// Maschere di rinomina di TC: "*.*" lascia il nome, "*.bak" cambia l'estensione, "copia di *.*" aggiunge un prefisso.
public enum NamePattern {
    public static func apply(_ pattern: String, to name: String) -> String {
        if pattern == "*.*" || pattern == "*" || pattern.isEmpty { return name }
        let ns = name as NSString
        let ext = ns.pathExtension
        let base = ext.isEmpty ? name : ns.deletingPathExtension
        let p = pattern as NSString
        let pExt = p.pathExtension
        let pBase = pExt.isEmpty && !pattern.hasSuffix(".") ? pattern : p.deletingPathExtension
        let newBase = pBase.replacingOccurrences(of: "*", with: base)
        if pExt.isEmpty && !pattern.contains(".") { return newBase + (ext.isEmpty ? "" : "." + ext) }
        let newExt = pExt.replacingOccurrences(of: "*", with: ext)
        return newExt.isEmpty ? newBase : newBase + "." + newExt
    }
}

public enum ConflictChoice: Equatable {
    case overwrite, skip, cancel, append
    case rename(String)
    /// Una scelta "tutti": vale per questo file e per i successivi.
    case policy(ConflictPolicy)
}

public enum ErrorChoice { case skip, cancel }
public enum TrashFallback { case deletePermanently, deleteAllPermanently, skip, cancel }

public struct TransferError: LocalizedError {
    public let message: String
    public init(_ message: String) { self.message = message }
    public var errorDescription: String? { message }
}

public struct TransferProgress {
    public var done: Int64 = 0
    public var total: Int64 = 0
    public var fileDone: Int64 = 0
    public var fileSize: Int64 = 0
    public var source: URL?
    public var destination: URL?
    public init() {}
}

/// Chiamate dal thread di lavoro: chi risponde a conflitti ed errori può bloccare.
public protocol TransferEngineDelegate: AnyObject {
    func engine(_ engine: TransferControl, progress: TransferProgress)
    func engine(_ engine: TransferControl, conflictAt destination: URL, source: URL) -> ConflictChoice
    func engine(_ engine: TransferControl, error: Error, at url: URL) -> ErrorChoice
    func engine(_ engine: TransferControl, trashFailedFor url: URL, error: Error) -> TrashFallback
}

/// Esegue un'operazione alla volta, in modo sincrono, sul thread che la chiama.
public final class TransferEngine {
    public weak var delegate: TransferEngineDelegate?

    private let lock = NSCondition()
    private var cancelled = false
    private var paused = false
    private var speedLimit: Int64?          // byte al secondo
    private var skipped = Set<URL>()
    private var _remaining: [(src: URL, dst: URL)] = []

    private let fm = FileManager()
    private var progress = TransferProgress()
    private var policy: ConflictPolicy = .ask
    private var trashPolicy: TrashFallback?
    private var job: TransferJob?
    private var throttleStart = Date()
    private var throttleBytes: Int64 = 0

    public init() {}

    // MARK: - Controlli dall'interfaccia (qualsiasi thread)

    public var isCancelled: Bool {
        lock.lock(); defer { lock.unlock() }
        return cancelled
    }

    /// Rimette data di creazione e modifica dell'originale (Impostazioni, attivo di solito).
    public var keepDates = true

    public func cancel() {
        lock.lock()
        cancelled = true
        paused = false
        lock.broadcast()
        lock.unlock()
    }

    public var isPaused: Bool {
        lock.lock(); defer { lock.unlock() }
        return paused
    }

    public func setPaused(_ p: Bool) {
        lock.lock()
        paused = p
        lock.broadcast()
        lock.unlock()
        resetThrottle()
    }

    /// nil = senza limite.
    public func setSpeedLimit(_ bytesPerSecond: Int64?) {
        lock.lock()
        speedLimit = bytesPerSecond.flatMap { $0 > 0 ? $0 : nil }
        lock.unlock()
        resetThrottle()
    }

    /// Elementi del lavoro non ancora iniziati (origine -> destinazione).
    public var remaining: [(src: URL, dst: URL)] {
        lock.lock(); defer { lock.unlock() }
        return _remaining.filter { !skipped.contains($0.src) }
    }

    /// Toglie un elemento non ancora iniziato.
    public func skip(_ src: URL) {
        lock.lock(); skipped.insert(src); lock.unlock()
    }

    private func isSkipped(_ src: URL) -> Bool {
        lock.lock(); defer { lock.unlock() }
        return skipped.contains(src)
    }

    private func waitIfPaused() {
        lock.lock()
        while paused && !cancelled { lock.wait() }
        lock.unlock()
    }

    private func currentLimit() -> Int64? {
        lock.lock(); defer { lock.unlock() }
        return speedLimit
    }

    private func resetThrottle() {
        throttleStart = Date()
        throttleBytes = 0
    }

    public enum Outcome { case completed, cancelled }

    @discardableResult
    public func run(_ job: TransferJob) -> Outcome {
        self.job = job
        policy = job.policy
        switch job.kind {
        case .trash, .delete: runDelete(job)
        case .copy, .move: runTransfer(job)
        case .pack, .extract: break   // li fa ArchiveTransfer
        }
        return isCancelled ? .cancelled : .completed
    }

    // MARK: - Elimina

    private func runDelete(_ job: TransferJob) {
        progress.total = Int64(job.sources.count)
        for (i, src) in job.sources.enumerated() {
            if isCancelled { return }
            progress.source = src
            progress.done = Int64(i)
            report()
            if job.kind == .trash && trashPolicy != .deleteAllPermanently {
                do {
                    try fm.trashItem(at: src, resultingItemURL: nil)
                    continue
                } catch {
                    let choice = delegate?.engine(self, trashFailedFor: src, error: error) ?? .skip
                    switch choice {
                    case .skip: continue
                    case .cancel: cancel(); return
                    case .deleteAllPermanently: trashPolicy = .deleteAllPermanently
                    case .deletePermanently: break
                    }
                }
            }
            do { try fm.removeItem(at: src) } catch {
                if ask(error, src) == .cancel { return }
            }
        }
        progress.done = progress.total
        report()
    }

    // MARK: - Copia e sposta

    private func runTransfer(_ job: TransferJob) {
        guard let destDir = job.destination?.standardizedFileURL else { return }
        if !lexists(destDir) {
            do { try fm.createDirectory(at: destDir, withIntermediateDirectories: true) } catch {
                _ = ask(error, destDir)
                return
            }
        }
        let move = job.kind == .move
        var plan: [(src: URL, dst: URL, rename: Bool)] = []
        for src in job.sources {
            let src = src.standardizedFileURL
            let dst = destDir.appendingPathComponent(job.targetName(for: src))
            if src.path == dst.path {
                if ask(TransferError("Origine e destinazione coincidono: \(src.lastPathComponent)"), src) == .cancel { return }
                continue
            }
            if isRealDir(src) && dst.path.hasPrefix(src.path + "/") {
                if ask(TransferError("Non si può copiare una cartella dentro se stessa: \(src.lastPathComponent)"), src) == .cancel { return }
                continue
            }
            plan.append((src, dst, move && job.fileMask == nil && sameVolume(src, destDir)))
        }
        lock.lock(); _remaining = plan.map { ($0.src, $0.dst) }; lock.unlock()

        progress.total = plan.filter { !$0.rename }.reduce(0) { $0 + size(of: $1.src, mask: job.fileMask) }
        progress.done = 0
        resetThrottle()
        for step in plan {
            waitIfPaused()
            if isCancelled { return }
            lock.lock(); _remaining.removeAll { $0.src == step.src }; lock.unlock()
            if isSkipped(step.src) {
                progress.total -= step.rename ? 0 : size(of: step.src, mask: job.fileMask)
                continue
            }
            if step.rename {
                progress.source = step.src
                progress.destination = step.dst
                report()
                _ = moveSameVolume(step.src, step.dst)
            } else {
                let ok = copyRecursive(step.src, step.dst)
                if ok && move && !isCancelled {
                    do { try fm.removeItem(at: step.src) } catch { if ask(error, step.src) == .cancel { return } }
                }
            }
        }
        progress.done = progress.total
        report()
    }

    private func moveSameVolume(_ src: URL, _ dst: URL) -> Bool {
        if isCancelled { return false }
        var dst = dst
        if lexists(dst) {
            if isRealDir(src) && isRealDir(dst) {
                // Unisce le cartelle, chiedendo per ogni file che esiste già.
                var all = true
                let children = (try? fm.contentsOfDirectory(at: src, includingPropertiesForKeys: nil)) ?? []
                for c in children where !moveSameVolume(c, dst.appendingPathComponent(c.lastPathComponent)) {
                    all = false
                }
                if all && !isCancelled { try? fm.removeItem(at: src) }
                return all
            }
            switch resolveConflict(src, dst) {
            case .overwrite:
                do { try fm.removeItem(at: dst) } catch { _ = ask(error, dst); return false }
            case .rename(let u):
                dst = u
                if lexists(dst) { return moveSameVolume(src, dst) }
            case .append:
                let ok = appendFile(src, to: dst)
                if ok { try? fm.removeItem(at: src) }
                return ok
            case .skip:
                return false
            }
        }
        do {
            try fm.moveItem(at: src, to: dst)
            return true
        } catch {
            _ = ask(error, src)
            return false
        }
    }

    /// true se l'elemento è stato copiato tutto (serve per lo spostamento: l'origine si cancella solo allora).
    private func copyRecursive(_ src: URL, _ dst: URL) -> Bool {
        waitIfPaused()
        if isCancelled { return false }
        if isRealDir(src) {
            if lexists(dst) && !isRealDir(dst) {
                switch resolveConflict(src, dst) {
                case .overwrite:
                    do { try fm.removeItem(at: dst) } catch { _ = ask(error, dst); return false }
                case .rename(let u):
                    return copyRecursive(src, u)
                default:
                    return false
                }
            }
            let created = !lexists(dst)
            if created {
                do { try fm.createDirectory(at: dst, withIntermediateDirectories: false) } catch {
                    _ = ask(error, dst)
                    return false
                }
            }
            let children: [URL]
            do { children = try fm.contentsOfDirectory(at: src, includingPropertiesForKeys: nil) } catch {
                _ = ask(error, src)
                return false
            }
            var all = true
            for c in children {
                if !copyRecursive(c, dst.appendingPathComponent(c.lastPathComponent)) { all = false }
                if isCancelled { return false }
            }
            // Con un filtro sui file, le cartelle rimaste vuote non servono.
            if job?.fileMask != nil && created && ((try? fm.contentsOfDirectory(atPath: dst.path))?.isEmpty ?? false) {
                try? fm.removeItem(at: dst)
            } else {
                // Date, permessi e attributi della cartella, dopo averla riempita.
                copyfile(src.path, dst.path, nil, copyfile_flags_t(CF.metadata))
                if keepDates { TransferEngine.copyDates(from: src, to: dst) }
            }
            return all
        }
        if let mask = job?.fileMask, !Matcher.matches(src.lastPathComponent, mask: mask) { return false }
        if lexists(dst) {
            switch resolveConflict(src, dst) {
            case .overwrite:
                do { try fm.removeItem(at: dst) } catch { _ = ask(error, dst); return false }
            case .rename(let u):
                return copyRecursive(src, u)
            case .append:
                return appendFile(src, to: dst)
            case .skip:
                progress.total -= fileSize(src)
                return false
            }
        }
        return copyFile(src, dst)
    }

    private func copyFile(_ src: URL, _ dst: URL) -> Bool {
        let size = fileSize(src)
        progress.source = src
        progress.destination = dst
        progress.fileDone = 0
        progress.fileSize = size
        report()

        let state = copyfile_state_alloc()
        defer { copyfile_state_free(state) }
        copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CB), unsafeBitCast(TransferEngine.callback, to: UnsafeRawPointer.self))
        copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CTX), Unmanaged.passUnretained(self).toOpaque())
        // Con il limite di velocità niente clonazione, altrimenti non c'è nulla da rallentare.
        var flags = CF.all | CF.excl | CF.nofollowSrc
        if currentLimit() == nil { flags |= CF.clone }
        let r = copyfile(src.path, dst.path, state, copyfile_flags_t(flags))
        if r != 0 {
            let code = errno
            if lexists(dst) { try? fm.removeItem(at: dst) }
            if isCancelled { return false }
            _ = ask(NSError(domain: NSPOSIXErrorDomain, code: Int(code)), src)
            return false
        }
        if keepDates { TransferEngine.copyDates(from: src, to: dst) }
        progress.done += size
        progress.fileDone = size
        report()
        if job?.verify == true && !sameContents(src, dst) {
            _ = ask(TransferError("Verifica non riuscita: la copia di \"\(src.lastPathComponent)\" è diversa dall'originale."), dst)
            return false
        }
        return true
    }

    /// "Accoda" del conflitto: aggiunge il file in fondo a quello esistente.
    /// Data di creazione e di modifica come l'originale. Sui dischi di rete (SMB, il NAS) copyfile
    /// lascia come creazione l'ora della copia, e le foto finiscono fuori ordine (es. sull'iPhone).
    public static func copyDates(from src: URL, to dst: URL) {
        let keys: Set<URLResourceKey> = [.creationDateKey, .contentModificationDateKey, .isSymbolicLinkKey]
        guard let v = try? src.resourceValues(forKeys: keys), v.isSymbolicLink != true else { return }
        var w = URLResourceValues()
        w.creationDate = v.creationDate
        w.contentModificationDate = v.contentModificationDate
        var d = dst
        d.removeAllCachedResourceValues()
        try? d.setResourceValues(w)
    }

    private func appendFile(_ src: URL, to dst: URL) -> Bool {
        do {
            let input = try FileHandle(forReadingFrom: src)
            let output = try FileHandle(forWritingTo: dst)
            defer { try? input.close(); try? output.close() }
            try output.seekToEnd()
            progress.source = src
            progress.destination = dst
            progress.fileDone = 0
            progress.fileSize = fileSize(src)
            while let chunk = try input.read(upToCount: 1 << 20), !chunk.isEmpty {
                waitIfPaused()
                if isCancelled { return false }
                try output.write(contentsOf: chunk)
                progress.fileDone += Int64(chunk.count)
                progress.done += Int64(chunk.count)
                throttle(Int64(chunk.count))
                report()
            }
            return true
        } catch {
            _ = ask(error, dst)
            return false
        }
    }

    fileprivate func fileProgress(_ copied: Int64) {
        let delta = copied - progress.fileDone
        progress.fileDone = copied
        throttle(delta)
        var p = progress
        p.done += copied
        delegate?.engine(self, progress: p)
    }

    private func throttle(_ bytes: Int64) {
        guard let limit = currentLimit(), bytes > 0 else { return }
        throttleBytes += bytes
        let expected = Double(throttleBytes) / Double(limit)
        let elapsed = Date().timeIntervalSince(throttleStart)
        if expected > elapsed { usleep(useconds_t(min(expected - elapsed, 5) * 1_000_000)) }
    }

    private static let callback: copyfile_callback_t = { what, stage, state, _, _, ctx in
        guard let ctx else { return COPYFILE_CONTINUE }
        let engine = Unmanaged<TransferEngine>.fromOpaque(ctx).takeUnretainedValue()
        engine.waitIfPaused()
        if engine.isCancelled { return COPYFILE_QUIT }
        if what == COPYFILE_COPY_DATA && stage == COPYFILE_PROGRESS {
            var copied: off_t = 0
            copyfile_state_get(state, UInt32(COPYFILE_STATE_COPIED), &copied)
            engine.fileProgress(Int64(copied))
        }
        return COPYFILE_CONTINUE
    }

    // MARK: - Conflitti

    private enum Resolution { case overwrite, skip, append, rename(URL) }

    private func resolveConflict(_ src: URL, _ dst: URL) -> Resolution {
        if policy == .ask {
            let c = delegate?.engine(self, conflictAt: dst, source: src) ?? .skip
            switch c {
            case .overwrite: return .overwrite
            case .skip: return .skip
            case .cancel: cancel(); return .skip
            case .append: return isRealDir(src) || isRealDir(dst) ? .skip : .append
            case .rename(let name): return .rename(dst.deletingLastPathComponent().appendingPathComponent(name))
            case .policy(let p): policy = p
            }
        }
        switch policy {
        case .ask, .skipAll: return .skip
        case .overwriteAll: return .overwrite
        case .overwriteOlder: return modified(dst) < modified(src) ? .overwrite : .skip
        case .overwriteSmaller: return fileSize(dst) < fileSize(src) ? .overwrite : .skip
        case .overwriteLarger: return fileSize(dst) > fileSize(src) ? .overwrite : .skip
        case .autoRename: return .rename(uniqueURL(dst))
        }
    }

    /// "nome (2).ext", "nome (3).ext"...
    func uniqueURL(_ u: URL) -> URL {
        let dir = u.deletingLastPathComponent()
        let ext = u.pathExtension
        let base = ext.isEmpty ? u.lastPathComponent : u.deletingPathExtension().lastPathComponent
        var n = 2
        while true {
            let name = "\(base) (\(n))" + (ext.isEmpty ? "" : ".\(ext)")
            let c = dir.appendingPathComponent(name)
            if !lexists(c) { return c }
            n += 1
        }
    }

    // MARK: - Aiuti

    private func report() {
        delegate?.engine(self, progress: progress)
    }

    private func ask(_ error: Error, _ url: URL) -> ErrorChoice {
        let c = delegate?.engine(self, error: error, at: url) ?? .skip
        if c == .cancel { cancel() }
        return c
    }

    private func size(of url: URL, mask: String?) -> Int64 {
        guard let mask else { return DirectoryLister.totalSize(of: url, isCancelled: { self.isCancelled }).bytes }
        if !isRealDir(url) { return Matcher.matches(url.lastPathComponent, mask: mask) ? fileSize(url) : 0 }
        var total: Int64 = 0
        let en = fm.enumerator(at: url, includingPropertiesForKeys: [.fileSizeKey, .isRegularFileKey])
        while let u = en?.nextObject() as? URL {
            let v = try? u.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey])
            if v?.isRegularFile == true && Matcher.matches(u.lastPathComponent, mask: mask) { total += Int64(v?.fileSize ?? 0) }
        }
        return total
    }

    private func fileSize(_ u: URL) -> Int64 {
        var st = stat()
        return lstat(u.path, &st) == 0 ? Int64(st.st_size) : 0
    }

    private func modified(_ u: URL) -> Date {
        var st = stat()
        guard lstat(u.path, &st) == 0 else { return .distantPast }
        return Date(timeIntervalSince1970: TimeInterval(st.st_mtimespec.tv_sec))
    }

    private func sameContents(_ a: URL, _ b: URL) -> Bool {
        guard let ha = try? FileHandle(forReadingFrom: a), let hb = try? FileHandle(forReadingFrom: b) else { return false }
        defer { try? ha.close(); try? hb.close() }
        while true {
            if isCancelled { return true }
            let da = (try? ha.read(upToCount: 1 << 20)) ?? Data()
            let db = (try? hb.read(upToCount: 1 << 20)) ?? Data()
            if da != db { return false }
            if da.isEmpty { return true }
        }
    }

    private func lexists(_ u: URL) -> Bool {
        var st = stat()
        return lstat(u.path, &st) == 0
    }

    private func isRealDir(_ u: URL) -> Bool {
        var st = stat()
        return lstat(u.path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR
    }

    private func sameVolume(_ a: URL, _ b: URL) -> Bool {
        var sa = stat(), sb = stat()
        guard lstat(a.path, &sa) == 0, stat(b.path, &sb) == 0 else { return false }
        return sa.st_dev == sb.st_dev
    }
}

/// Valori di copyfile.h (alcuni sono macro composte che Swift non importa).
enum CF {
    static let acl: UInt32 = 1 << 0
    static let stat: UInt32 = 1 << 1
    static let xattr: UInt32 = 1 << 2
    static let data: UInt32 = 1 << 3
    static let metadata: UInt32 = acl | stat | xattr
    static let all: UInt32 = metadata | data
    static let excl: UInt32 = 1 << 17
    static let nofollowSrc: UInt32 = 1 << 18
    static let clone: UInt32 = 1 << 24
}
