import Foundation
import CArchiveShim

/// Archivi come cartelle (come in TC): "~/Download/foto.zip/2024/a.jpg" è il file "2024/a.jpg"
/// dentro foto.zip. Si leggono e si scrivono con la libarchive di macOS.
/// File arrivati da fuori (FTP, archivi) che l'app apre: macOS li tratta come scaricati,
/// così Gatekeeper controlla programmi e script prima di aprirli.
public enum Quarantine {
    public static func mark(_ url: URL) {
        var u = url
        var v = URLResourceValues()
        v.quarantineProperties = ["LSQuarantineType": "LSQuarantineTypeOtherDownload", "LSQuarantineAgentName": "Mac Commander"]
        try? u.setResourceValues(v)
    }
}

public enum ArchivePath {
    /// Estensioni in cui si entra con Invio. Gli altri formati che libarchive conosce
    /// (docx, epub…) si aprono normalmente, ma ci si entra con Ctrl+PgGiù.
    public static let extensions: Set<String> = ["zip", "rar", "7z", "tar", "tgz", "tbz", "tbz2", "txz", "gz", "bz2", "xz",
                                                 "cab", "iso", "jar", "cpio", "lzh", "lha", "xar", "cbz", "cbr", "cb7", "z", "lz", "lzma", "zipx"]

    public static func isArchiveName(_ name: String) -> Bool {
        extensions.contains((name as NSString).pathExtension.lowercased())
    }

    /// Archivio e percorso interno ("" = la radice dell'archivio). nil se non c'entra un archivio.
    /// `anyFile`: vale anche per file con altre estensioni (Ctrl+PgGiù su un docx).
    public static func split(_ url: URL, anyFile: Bool = false) -> (archive: URL, inner: String)? {
        guard url.isFileURL else { return nil }
        let comps = url.standardizedFileURL.pathComponents
        // Prima un controllo senza toccare il disco: serve un pezzo del percorso con un'estensione da archivio.
        guard anyFile || comps.contains(where: isArchiveName) else { return nil }
        var isDir: ObjCBool = false
        if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) {
            if isDir.boolValue { return nil }
            return anyFile || isArchiveName(url.lastPathComponent) ? (url.standardizedFileURL, "") : nil
        }
        // Il percorso non esiste: si risale fino al primo pezzo che esiste, e deve essere un archivio.
        for i in stride(from: comps.count - 1, to: 0, by: -1) {
            let base = NSString.path(withComponents: Array(comps[..<i]))
            if FileManager.default.fileExists(atPath: base, isDirectory: &isDir) {
                guard !isDir.boolValue, anyFile || isArchiveName(comps[i - 1]) else { return nil }
                return (URL(fileURLWithPath: base), comps[i...].joined(separator: "/"))
            }
        }
        return nil
    }

    /// Un file o una cartella dentro un archivio (non l'archivio stesso).
    public static func isInside(_ url: URL) -> Bool {
        guard let s = split(url) else { return false }
        return !s.inner.isEmpty
    }

    /// Il pannello mostra l'archivio: la sua radice o una cartella interna.
    public static func isBrowsable(_ url: URL) -> Bool { split(url) != nil }
}

public struct ArchiveEntry {
    public let path: String
    public let isDirectory: Bool
    public let size: Int64
    public let modified: Date?
}

public struct ArchiveError: LocalizedError {
    public let message: String
    public let needsPassword: Bool
    public var errorDescription: String? { message }
}

/// Il contenuto di un archivio, letto una volta e tenuto finché il file non cambia.
public final class ArchiveIndex {
    public let entries: [String: ArchiveEntry]
    let children: [String: [String]]
    let stamp: String

    init(entries list: [ArchiveEntry], stamp: String) {
        var e: [String: ArchiveEntry] = [:]
        var ch: [String: Set<String>] = [:]
        for x in list {
            e[x.path] = x
            // Le cartelle intermedie non sempre sono nell'archivio: si aggiungono.
            var p = x.path
            while true {
                let parent = (p as NSString).deletingLastPathComponent
                ch[parent, default: []].insert(p)
                if parent.isEmpty { break }
                if e[parent] == nil { e[parent] = ArchiveEntry(path: parent, isDirectory: true, size: 0, modified: x.modified) }
                p = parent
            }
        }
        entries = e
        children = ch.mapValues { Array($0) }
        self.stamp = stamp
    }

    /// Tutto quello che sta sotto `inner` (compreso `inner`).
    func entries(under inner: String) -> [ArchiveEntry] {
        if inner.isEmpty { return Array(entries.values) }
        let prefix = inner + "/"
        return entries.values.filter { $0.path == inner || $0.path.hasPrefix(prefix) }
    }
}

public enum ArchiveReader {
    private static let lock = NSLock()
    private static var cache: [String: ArchiveIndex] = [:]
    private static var passwords: [String: String] = [:]

    /// Chiede la password di un archivio protetto (lo imposta l'app; si chiama da un thread di lavoro).
    public static var passwordProvider: ((URL) -> String?)?

    static func password(for archive: URL) -> String? {
        lock.lock(); defer { lock.unlock() }
        return passwords[archive.path]
    }

    /// Chiede la password e la ricorda finché l'app è aperta (come "Ricorda l'ultima password" di TC).
    static func askPassword(for archive: URL) -> String? {
        guard let p = passwordProvider?(archive), !p.isEmpty else { return nil }
        lock.lock(); passwords[archive.path] = p; lock.unlock()
        return p
    }

    private static func stamp(_ url: URL) -> String {
        let v = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey])
        return "\(v?.contentModificationDate?.timeIntervalSince1970 ?? 0)-\(v?.fileSize ?? 0)"
    }

    /// Nome dell'elemento: UTF-8 se c'è, altrimenti i vecchi zip di Windows (CP850).
    static func entryPath(_ e: OpaquePointer) -> String? {
        var raw: String?
        if let p = archive_entry_pathname_utf8(e) { raw = String(cString: p) }
        else if let p = archive_entry_pathname(e) {
            let data = Data(bytes: p, count: strlen(p))
            let cp850 = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(0x0410)))
            raw = String(data: data, encoding: .utf8) ?? String(data: data, encoding: cp850) ?? String(data: data, encoding: .windowsCP1252)
        }
        guard let raw else { return nil }
        // Niente "/" iniziali, "./" o "..": un archivio non deve poter scrivere fuori dalla destinazione.
        let parts = raw.replacingOccurrences(of: "\\", with: "/").split(separator: "/").filter { $0 != "." && $0 != ".." && !$0.isEmpty }
        return parts.isEmpty ? nil : parts.joined(separator: "/")
    }

    static func open(_ archive: URL, password: String?) throws -> OpaquePointer {
        guard let a = archive_read_new() else { throw ArchiveError(message: "libarchive non disponibile", needsPassword: false) }
        archive_read_support_filter_all(a)
        archive_read_support_format_all(a)
        if let password { archive_read_add_passphrase(a, password) }
        if archive_read_open_filename(a, archive.path, 1 << 20) != MC_ARCHIVE_OK {
            let e = error(a)
            archive_read_free(a)
            throw e
        }
        return a
    }

    static func error(_ a: OpaquePointer) -> ArchiveError {
        let msg = archive_error_string(a).map { String(cString: $0) } ?? "Archivio non leggibile"
        let low = msg.lowercased()
        let pw = low.contains("passphrase") || low.contains("password") || low.contains("encrypt")
        return ArchiveError(message: pw ? "L'archivio è protetto da password" : msg, needsPassword: pw)
    }

    /// Rifà l'operazione chiedendo la password se l'archivio la vuole.
    static func withPassword<T>(_ archive: URL, _ body: (String?) throws -> T) throws -> T {
        do { return try body(password(for: archive)) } catch let e as ArchiveError where e.needsPassword {
            while let p = askPassword(for: archive) {
                do { return try body(p) } catch let e2 as ArchiveError where e2.needsPassword { continue }
            }
            throw e
        }
    }

    public static func index(_ archive: URL) throws -> ArchiveIndex {
        let st = stamp(archive)
        lock.lock()
        if let c = cache[archive.path], c.stamp == st { lock.unlock(); return c }
        lock.unlock()
        let list: [ArchiveEntry] = try withPassword(archive) { pw in
            let a = try open(archive, password: pw)
            defer { archive_read_free(a) }
            var out: [ArchiveEntry] = []
            var e: OpaquePointer?
            while true {
                let r = archive_read_next_header(a, &e)
                if r == MC_ARCHIVE_EOF { break }
                if r < MC_ARCHIVE_WARN { throw error(a) }
                guard let e, let path = entryPath(e) else { continue }
                let type = archive_entry_filetype(e) & mode_t(MC_AE_IFMT)
                let mtime = archive_entry_mtime_is_set(e) != 0 ? Date(timeIntervalSince1970: TimeInterval(archive_entry_mtime(e))) : nil
                out.append(ArchiveEntry(path: path, isDirectory: type == mode_t(MC_AE_IFDIR), size: archive_entry_size(e), modified: mtime))
            }
            return out
        }
        let idx = ArchiveIndex(entries: list, stamp: st)
        lock.lock(); cache[archive.path] = idx; lock.unlock()
        return idx
    }

    /// Righe del pannello per una cartella dentro l'archivio.
    public static func list(_ archive: URL, inner: String) throws -> [FileItem] {
        let idx = try index(archive)
        if !inner.isEmpty && idx.entries[inner]?.isDirectory != true {
            throw ArchiveError(message: "\"\(inner)\" non c'è nell'archivio", needsPassword: false)
        }
        let base = inner.isEmpty ? archive : archive.appendingPathComponent(inner)
        return (idx.children[inner] ?? []).compactMap { p in
            guard let e = idx.entries[p] else { return nil }
            let name = (p as NSString).lastPathComponent
            return FileItem(url: base.appendingPathComponent(name), name: name, isDirectory: e.isDirectory,
                            isHidden: name.hasPrefix("."), size: e.size, modified: e.modified)
        }
    }

    /// Estrae in una cartella temporanea un file dell'archivio (per aprirlo, F3, F4).
    public static func extractToTemp(_ url: URL) throws -> URL {
        guard let (archive, inner) = ArchivePath.split(url), !inner.isEmpty else { return url }
        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("Mac Commander/\(abs(archive.path.hashValue))")
        let dst = dir.appendingPathComponent((inner as NSString).lastPathComponent)
        try? FileManager.default.removeItem(at: dst)
        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
        try extract(archive, target: { $0 == inner ? dst : nil })
        Quarantine.mark(dst)
        return dst
    }

    /// Legge l'archivio una volta e scrive gli elementi per cui `target` dà una destinazione.
    /// `decide` risolve i file che esistono già: la destinazione finale, o nil per saltarli.
    /// Chiamata sul thread di lavoro.
    public static func extract(_ archive: URL, target: (String) -> URL?,
                               decide: (ArchiveEntry, URL) -> URL? = { $1 },
                               progress: (Int64) -> Void = { _ in }, isCancelled: () -> Bool = { false }) throws {
        try withPassword(archive) { pw in
            let a = try open(archive, password: pw)
            defer { archive_read_free(a) }
            let fm = FileManager()
            var buffer = [UInt8](repeating: 0, count: 1 << 20)
            var e: OpaquePointer?
            while !isCancelled() {
                let r = archive_read_next_header(a, &e)
                if r == MC_ARCHIVE_EOF { break }
                if r < MC_ARCHIVE_WARN { throw error(a) }
                guard let e, let path = entryPath(e), var dst = target(path) else { continue }
                let type = archive_entry_filetype(e) & mode_t(MC_AE_IFMT)
                let mtime = archive_entry_mtime_is_set(e) != 0 ? Date(timeIntervalSince1970: TimeInterval(archive_entry_mtime(e))) : nil
                let entry = ArchiveEntry(path: path, isDirectory: type == mode_t(MC_AE_IFDIR), size: archive_entry_size(e), modified: mtime)
                if entry.isDirectory {
                    try fm.createDirectory(at: dst, withIntermediateDirectories: true)
                    if let mtime { try? fm.setAttributes([.modificationDate: mtime, .creationDate: mtime], ofItemAtPath: dst.path) }
                    continue
                }
                try fm.createDirectory(at: dst.deletingLastPathComponent(), withIntermediateDirectories: true)
                var st = stat()
                if lstat(dst.path, &st) == 0 {
                    guard let d = decide(entry, dst) else { continue }
                    dst = d
                }
                // I collegamenti dentro gli archivi non si estraggono: potrebbero puntare fuori dalla
                // destinazione e far scrivere lì i file che seguono.
                if type == mode_t(MC_AE_IFLNK) { continue }
                if archive_entry_is_encrypted(e) != 0 && pw == nil {
                    throw ArchiveError(message: "L'archivio è protetto da password", needsPassword: true)
                }
                let tmp = dst.deletingLastPathComponent().appendingPathComponent(".\(dst.lastPathComponent).mc-part")
                guard let out = fopen(tmp.path, "wb") else {
                    throw ArchiveError(message: "Non riesco a scrivere \(dst.path): \(String(cString: strerror(errno)))", needsPassword: false)
                }
                var ok = true
                while true {
                    if isCancelled() { ok = false; break }
                    let n = buffer.withUnsafeMutableBytes { archive_read_data(a, $0.baseAddress, $0.count) }
                    if n == 0 { break }
                    if n < 0 {
                        fclose(out)
                        try? fm.removeItem(at: tmp)
                        throw error(a)
                    }
                    if buffer.withUnsafeBytes({ fwrite($0.baseAddress, 1, n, out) }) != n {
                        fclose(out)
                        try? fm.removeItem(at: tmp)
                        throw ArchiveError(message: "Scrittura non riuscita: \(dst.path)", needsPassword: false)
                    }
                    progress(Int64(n))
                }
                fclose(out)
                guard ok else { try? fm.removeItem(at: tmp); return }
                try? fm.removeItem(at: dst)
                try fm.moveItem(at: tmp, to: dst)
                let perm = archive_entry_perm(e)
                if perm & 0o111 != 0 { chmod(dst.path, 0o755) }
                if let mtime { try? fm.setAttributes([.modificationDate: mtime, .creationDate: mtime], ofItemAtPath: dst.path) }
            }
        }
    }

    /// Option+Shift+F9: legge tutto l'archivio per vedere se è integro. nil = tutto a posto.
    public static func test(_ archive: URL, isCancelled: () -> Bool = { false }) -> String? {
        do {
            try withPassword(archive) { pw in
                let a = try open(archive, password: pw)
                defer { archive_read_free(a) }
                var buffer = [UInt8](repeating: 0, count: 1 << 20)
                var e: OpaquePointer?
                while !isCancelled() {
                    let r = archive_read_next_header(a, &e)
                    if r == MC_ARCHIVE_EOF { break }
                    if r < MC_ARCHIVE_WARN { throw error(a) }
                    while true {
                        let n = buffer.withUnsafeMutableBytes { archive_read_data(a, $0.baseAddress, $0.count) }
                        if n == 0 { break }
                        if n < 0 { throw error(a) }
                    }
                }
            }
            return nil
        } catch {
            return error.localizedDescription
        }
    }
}

public enum ArchiveFormat: String, CaseIterable {
    case zip, sevenZip = "7z", tar, tgz = "tar.gz"

    public var title: String {
        switch self {
        case .zip: return "ZIP"
        case .sevenZip: return "7Z"
        case .tar: return "TAR"
        case .tgz: return "TAR.GZ"
        }
    }

    public static func from(_ url: URL) -> ArchiveFormat? {
        let name = url.lastPathComponent.lowercased()
        if name.hasSuffix(".tar.gz") || name.hasSuffix(".tgz") { return .tgz }
        return ArchiveFormat(rawValue: url.pathExtension.lowercased())
    }
}

public enum ArchiveWriter {
    /// Comprime `sources` (file e cartelle, con il loro nome) in un nuovo archivio.
    /// I .DS_Store del Mac restano fuori. Scrive in un file temporaneo e lo rinomina alla fine.
    public static func pack(_ sources: [URL], to archive: URL, format: ArchiveFormat,
                            progress: (URL, Int64) -> Void = { _, _ in }, isCancelled: () -> Bool = { false }) throws {
        guard let a = archive_write_new() else { throw ArchiveError(message: "libarchive non disponibile", needsPassword: false) }
        defer { archive_write_free(a) }
        switch format {
        case .zip:
            archive_write_set_format_zip(a)
            _ = archive_write_set_options(a, "zip:compression-level=9")
            _ = archive_write_set_options(a, "zip:hdrcharset=UTF-8")
        case .sevenZip:
            archive_write_set_format_7zip(a)
        case .tar:
            archive_write_set_format_pax_restricted(a)
        case .tgz:
            archive_write_set_format_pax_restricted(a)
            archive_write_add_filter_gzip(a)
        }
        let tmp = archive.deletingLastPathComponent().appendingPathComponent(".\(archive.lastPathComponent).mc-part")
        try? FileManager.default.removeItem(at: tmp)
        guard archive_write_open_filename(a, tmp.path) == MC_ARCHIVE_OK else { throw ReaderError.from(a) }
        var ok = false
        defer { if !ok { try? FileManager.default.removeItem(at: tmp) } }

        let fm = FileManager()
        var buffer = [UInt8](repeating: 0, count: 1 << 20)
        func add(_ url: URL, as path: String) throws {
            if isCancelled() { return }
            guard url.lastPathComponent != ".DS_Store" else { return }
            let attrs = try fm.attributesOfItem(atPath: url.path)
            let type = attrs[.type] as? FileAttributeType
            guard let entry = archive_entry_new() else { return }
            defer { archive_entry_free(entry) }
            archive_entry_set_pathname_utf8(entry, path)
            let mtime = (attrs[.modificationDate] as? Date) ?? Date()
            archive_entry_set_mtime(entry, time_t(mtime.timeIntervalSince1970), 0)
            archive_entry_set_perm(entry, mode_t((attrs[.posixPermissions] as? Int) ?? 0o644))
            if type == .typeDirectory {
                archive_entry_set_filetype(entry, UInt32(MC_AE_IFDIR))
                archive_entry_set_size(entry, 0)
                guard archive_write_header(a, entry) >= MC_ARCHIVE_WARN else { throw ReaderError.from(a) }
                let children = try fm.contentsOfDirectory(atPath: url.path).sorted()
                for c in children { try add(url.appendingPathComponent(c), as: path + "/" + c) }
                return
            }
            guard type == .typeRegular else { return }   // collegamenti e file speciali restano fuori
            let size = (attrs[.size] as? NSNumber)?.int64Value ?? 0
            archive_entry_set_filetype(entry, UInt32(MC_AE_IFREG))
            archive_entry_set_size(entry, size)
            guard archive_write_header(a, entry) >= MC_ARCHIVE_WARN else { throw ReaderError.from(a) }
            guard let f = fopen(url.path, "rb") else {
                throw ArchiveError(message: "Non riesco a leggere \(url.path): \(String(cString: strerror(errno)))", needsPassword: false)
            }
            defer { fclose(f) }
            while !isCancelled() {
                let n = buffer.withUnsafeMutableBytes { fread($0.baseAddress, 1, $0.count, f) }
                if n == 0 { break }
                let w = buffer.withUnsafeBytes { archive_write_data(a, $0.baseAddress, n) }
                if w < 0 { throw ReaderError.from(a) }
                progress(url, Int64(n))
            }
        }
        for s in sources {
            try add(s, as: s.lastPathComponent)
            if isCancelled() { return }
        }
        guard archive_write_close(a) == MC_ARCHIVE_OK else { throw ReaderError.from(a) }
        try? fm.removeItem(at: archive)
        try fm.moveItem(at: tmp, to: archive)
        ok = true
    }

    private enum ReaderError {
        static func from(_ a: OpaquePointer) -> ArchiveError { ArchiveReader.error(a) }
    }
}
