import Foundation

/// I RAR "solidi" (e alcuni metodi RAR vecchi) la libarchive del Mac non li sa scompattare:
/// per i .rar si usa 7-Zip (`7zz`), se c'è: dentro l'app o installato (brew install sevenzip).
public enum SevenZip {
    /// Il 7zz dentro Mac Commander.app (lo imposta l'app all'avvio).
    public static var bundled: URL?

    public static var executable: URL? {
        if let b = bundled, FileManager.default.isExecutableFile(atPath: b.path) { return b }
        for p in ["/opt/homebrew/bin/7zz", "/usr/local/bin/7zz"] where FileManager.default.isExecutableFile(atPath: p) {
            return URL(fileURLWithPath: p)
        }
        return nil
    }

    /// I .rar passano da 7-Zip quando c'è.
    static func handles(_ archive: URL) -> Bool {
        let ext = archive.pathExtension.lowercased()
        return (ext == "rar" || ext == "cbr") && executable != nil
    }

    // MARK: - Esecuzione

    private final class Runner {
        let process = Process()
        var output = Data()
    }

    /// Esegue 7zz; `line` riceve l'avanzamento (righe con la percentuale). Errore se il codice d'uscita non è 0.
    @discardableResult
    static func run(_ args: [String], password: String? = nil, isCancelled: () -> Bool = { false }, line: (String) -> Void = { _ in }) throws -> String {
        guard let exe = executable else {
            throw ArchiveError(message: "Per questo archivio serve 7-Zip", needsPassword: false)
        }
        let p = Process()
        p.executableURL = exe
        // La password non va sulla riga di comando (la vedrebbe chiunque guardi i processi):
        // 7-Zip la chiede e la riceve dallo standard input. Senza password se ne passa una finta.
        p.arguments = password == nil ? args.map { $0 == "@PW" ? "-p-" : $0 } : args.filter { $0 != "@PW" }
        let input = Pipe()
        p.standardInput = password == nil ? FileHandle.nullDevice : input
        let out = Pipe()
        p.standardOutput = out
        p.standardError = out
        // I dati arrivano su un altro thread; l'avanzamento si legge qui, ogni decimo di secondo.
        final class Box { var data = Data(); let lock = NSLock() }
        let box = Box()
        out.fileHandleForReading.readabilityHandler = { h in
            let d = h.availableData
            guard !d.isEmpty else { return }
            box.lock.lock(); box.data.append(d); box.lock.unlock()
        }
        var seen = 0
        func pump() {
            box.lock.lock()
            let new = box.data.count > seen ? box.data.subdata(in: seen..<box.data.count) : Data()
            seen = box.data.count
            box.lock.unlock()
            if let s = String(data: new, encoding: .utf8) {
                for part in s.components(separatedBy: CharacterSet(charactersIn: "\r\n\u{8}")) where !part.isEmpty { line(part) }
            }
        }
        try p.run()
        if let password {
            // Una riga per ogni richiesta possibile (elenco ed estrazione), poi si chiude.
            let line = Data((password + "\n").utf8)
            try? input.fileHandleForWriting.write(contentsOf: line + line)
            try? input.fileHandleForWriting.close()
        }
        while p.isRunning {
            if isCancelled() { p.terminate(); break }
            pump()
            Thread.sleep(forTimeInterval: 0.1)
        }
        p.waitUntilExit()
        out.fileHandleForReading.readabilityHandler = nil
        let rest = out.fileHandleForReading.readDataToEndOfFile()
        box.lock.lock(); box.data.append(rest); box.lock.unlock()
        pump()
        let text = String(data: box.data, encoding: .utf8) ?? ""
        if isCancelled() { return text }
        guard p.terminationStatus == 0 else {
            let low = text.lowercased()
            if low.contains("wrong password") || low.contains("encrypted") && low.contains("can not open") {
                throw ArchiveError(message: "L'archivio è protetto da password", needsPassword: true)
            }
            let msg = text.components(separatedBy: .newlines).first { $0.contains("ERROR") || $0.contains("Error") } ?? "7-Zip non riesce a leggere l'archivio"
            throw ArchiveError(message: msg.trimmingCharacters(in: .whitespaces), needsPassword: false)
        }
        return text
    }


    // MARK: - Elenco

    private static let dateFormat: DateFormatter = {
        let f = DateFormatter()
        f.locale = Locale(identifier: "en_US_POSIX")
        f.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return f
    }()

    static func list(_ archive: URL, password: String?) throws -> [ArchiveEntry] {
        let text = try run(["l", "-slt", "-ba", "-sccUTF-8", "@PW", archive.path], password: password)
        var out: [ArchiveEntry] = []
        var cur: [String: String] = [:]
        func flush() {
            defer { cur = [:] }
            guard let raw = cur["Path"] else { return }
            // I collegamenti non si estraggono (potrebbero puntare fuori dalla destinazione), come con libarchive.
            if !(cur["Symbolic Link"] ?? "").isEmpty || (cur["Attributes"] ?? "").contains(" l") { return }
            let parts = raw.replacingOccurrences(of: "\\", with: "/").split(separator: "/").filter { $0 != "." && $0 != ".." && !$0.isEmpty }
            guard !parts.isEmpty else { return }
            let date = cur["Modified"].flatMap { dateFormat.date(from: String($0.prefix(19))) }
            out.append(ArchiveEntry(path: parts.joined(separator: "/"), isDirectory: cur["Folder"] == "+",
                                    size: Int64(cur["Size"] ?? "") ?? 0, modified: date))
        }
        for line in text.components(separatedBy: .newlines) {
            if line.isEmpty { flush(); continue }
            guard let r = line.range(of: " = ") else { continue }
            cur[String(line[..<r.lowerBound])] = String(line[r.upperBound...])
        }
        flush()
        return out
    }

    // MARK: - Estrazione

    /// Estrae in `dir` solo gli elementi indicati (percorsi esatti), con l'avanzamento da 0 a 1.
    static func extract(_ archive: URL, paths: [String], to dir: URL, password: String?,
                        progress: (Double) -> Void, isCancelled: () -> Bool) throws {
        let listFile = FileManager.default.temporaryDirectory.appendingPathComponent("mc-7z-\(UUID().uuidString).txt")
        try paths.joined(separator: "\n").write(to: listFile, atomically: true, encoding: .utf8)
        defer { try? FileManager.default.removeItem(at: listFile) }
        // -spd: i nomi con [ ] o * non sono maschere; -bsp1: avanzamento in percentuale.
        try run(["x", "-y", "-aoa", "-bsp1", "-bso0", "-spd", "-scsUTF-8", "-sccUTF-8", "@PW",
                 "-o" + dir.path, archive.path, "@" + listFile.path], password: password, isCancelled: isCancelled) { line in
            let t = line.trimmingCharacters(in: .whitespaces)
            if let pct = t.split(separator: "%").first.flatMap({ Int($0.trimmingCharacters(in: .whitespaces)) }), t.contains("%") {
                progress(Double(pct) / 100)
            }
        }
    }

    static func test(_ archive: URL, password: String?) throws {
        try run(["t", "-bso0", "-sccUTF-8", "@PW", archive.path], password: password)
    }
}
