import Foundation

/// Le connessioni salvate, in "Application Support/Mac Commander/ftp.json" (senza password).
public enum FtpStore {
    public static var defaultURL: URL {
        HotlistStore.defaultURL.deletingLastPathComponent().appendingPathComponent("ftp.json")
    }

    public static func load(from url: URL = defaultURL) -> [FtpConnection] {
        guard let data = try? Data(contentsOf: url),
              let list = try? JSONDecoder().decode([FtpConnection].self, from: data) else { return [] }
        return list
    }

    public static func save(_ list: [FtpConnection], to url: URL = defaultURL) throws {
        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
        let enc = JSONEncoder()
        enc.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes, .sortedKeys]
        try enc.encode(list.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }).write(to: url, options: .atomic)
    }
}

/// Importazione da wcx_ftp.ini di Total Commander.
public enum TCFtpImport {
    public struct Imported {
        public var connection: FtpConnection
        /// La password decodificata, se richiesta e se valida.
        public var password: String?
    }

    /// Le cartelle locali di Windows (C:\..., D:\...) sul Mac non esistono: si lasciano vuote
    /// e si scelgono nella finestra delle connessioni.
    public static func translateLocalDir(_ win: String) -> String { "" }

    public static func parse(_ text: String, withPasswords: Bool) -> [Imported] {
        var sections: [String: [String: String]] = [:]
        var order: [String] = []
        var current: String?
        for raw in text.components(separatedBy: .newlines) {
            let line = raw.trimmingCharacters(in: .whitespaces)
            if line.hasPrefix("[") && line.hasSuffix("]") {
                current = String(line.dropFirst().dropLast())
                if let c = current, sections[c] == nil { sections[c] = [:]; order.append(c) }
                continue
            }
            guard let c = current, let eq = line.firstIndex(of: "=") else { continue }
            sections[c]?[String(line[..<eq]).lowercased()] = String(line[line.index(after: eq)...])
        }
        var out: [Imported] = []
        for name in order {
            guard !["connections", "general", "default"].contains(name.lowercased()),
                  let s = sections[name], var host = s["host"], !host.isEmpty else { continue }
            var conn = FtpConnection(name: name.replacingOccurrences(of: "\\", with: "|"), host: host)
            let lower = host.lowercased()
            if lower.hasPrefix("ftpis://") { conn.implicitTLS = true; host = String(host.dropFirst(8)) }
            else if lower.hasPrefix("ftpes://") { conn.tls = true; host = String(host.dropFirst(8)) }
            else if lower.hasPrefix("ftps://") { conn.tls = true; host = String(host.dropFirst(7)) }
            else if lower.hasPrefix("ftp://") { host = String(host.dropFirst(6)) }
            conn.host = host
            conn.user = s["username"] ?? ""
            conn.remoteDir = s["directory"] ?? ""
            conn.localDir = translateLocalDir(s["localdir"] ?? "")
            conn.passive = (s["pasvmode"] ?? "1") != "0"
            var pwd: String?
            if withPasswords, let enc = s["password"], !enc.isEmpty, !enc.hasPrefix("!") {
                pwd = TCPassword.decode(enc)
            }
            out.append(Imported(connection: conn, password: pwd))
        }
        return out
    }
}

/// Le password FTP di TC (senza password principale) non sono cifrate davvero: sono mescolate con
/// il generatore pseudo-casuale di Delphi a semi fissi. Qui si fa il percorso inverso, per importarle
/// nel Portachiavi: rotazione a sinistra, 256 scambi, XOR, sottrazione. Gli ultimi 4 byte sono un controllo.
/// Le password con la password principale di TC ("!…", AES) non si possono leggere.
public enum TCPassword {
    private struct Rand {
        var seed: UInt32
        mutating func next(_ max: UInt32) -> UInt32 {
            seed = seed &* 0x8088405 &+ 1
            return UInt32((UInt64(seed) * UInt64(max)) >> 32)
        }
    }

    public static func decode(_ hex: String) -> String? {
        var b: [UInt8] = []
        var i = hex.startIndex
        while i < hex.endIndex, let j = hex.index(i, offsetBy: 2, limitedBy: hex.endIndex) {
            guard let v = UInt8(hex[i..<j], radix: 16) else { return nil }
            b.append(v)
            i = j
        }
        guard b.count > 4, hex.count % 2 == 0 else { return nil }
        let n = b.count - 4
        var r = Rand(seed: 849521)
        for k in 0..<n {
            let s = UInt8(r.next(8))
            b[k] = s == 0 ? b[k] : (b[k] << s) | (b[k] >> (8 - s))
        }
        r = Rand(seed: 12345)
        for _ in 0..<256 {
            let x = Int(r.next(UInt32(n))), y = Int(r.next(UInt32(n)))
            b.swapAt(x, y)
        }
        r = Rand(seed: 42340)
        for k in 0..<n { b[k] ^= UInt8(r.next(256)) }
        r = Rand(seed: 54321)
        for k in 0..<n { b[k] = b[k] &- UInt8(r.next(256)) }
        let out = Array(b[0..<n])
        // Testo stampabile, altrimenti meglio chiedere la password che sbagliarla.
        guard out.allSatisfy({ $0 >= 0x20 && $0 != 0x7F }) else { return nil }
        return String(bytes: out, encoding: .utf8) ?? String(bytes: out, encoding: .windowsCP1252)
    }

    /// Il contrario di `decode` (per le prove).
    static func encode(_ password: String) -> String {
        var b = Array(password.utf8)
        let n = b.count
        var r = Rand(seed: 54321)
        for k in 0..<n { b[k] = b[k] &+ UInt8(r.next(256)) }
        r = Rand(seed: 42340)
        for k in 0..<n { b[k] ^= UInt8(r.next(256)) }
        r = Rand(seed: 12345)
        var swaps: [(Int, Int)] = []
        for _ in 0..<256 { swaps.append((Int(r.next(UInt32(n))), Int(r.next(UInt32(n))))) }
        for (x, y) in swaps.reversed() { b.swapAt(x, y) }
        r = Rand(seed: 849521)
        for k in 0..<n {
            let s = UInt8(r.next(8))
            b[k] = s == 0 ? b[k] : (b[k] >> s) | (b[k] << (8 - s))
        }
        return (b + [0, 0, 0, 0]).map { String(format: "%02X", $0) }.joined()
    }
}
