import 'dart:convert';
import 'dart:math';

/// AES 会话密钥实体 — 对齐老项目
///
/// 每个聊天室独有的 32-char alphanumeric ASCII 字符串。
/// UTF-8 编码恰好 32 bytes，匹配 iOS `key.utf8.count == 32`。
class SessionKey {
  /// 32-char alphanumeric ASCII 会话密钥
  final String key;

  /// 密钥轮换 round 值
  final int round;

  const SessionKey({
    required this.key,
    required this.round,
  });

  /// 生成随机会话密钥（32-char alphanumeric）
  ///
  /// 对齐老项目 `getRandomString(32)`。
  static SessionKey generate({int initialRound = 1}) {
    const chars =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    final random = Random.secure();
    final key = String.fromCharCodes(
      List.generate(32, (_) => chars.codeUnitAt(random.nextInt(chars.length))),
    );
    return SessionKey(key: key, round: initialRound);
  }

  /// 根据 round 值通过 MD5 hash chain 计算对应密钥
  ///
  /// 对齐老项目 `getCalculatedKey(chat, roundToCheck)`：
  /// ```dart
  /// for (int i = 0; i < numberOfTimes; i++) {
  ///     currentKey = makeMD5(currentKey);
  /// }
  /// ```
  ///
  /// 每次 round 递增，key 经过一次 MD5 哈希。
  SessionKey forRound(int targetRound) {
    if (targetRound <= round) return this;

    var currentKey = key;
    final numberOfTimes = targetRound - round;
    for (var i = 0; i < numberOfTimes; i++) {
      currentKey = _makeMd5(currentKey);
    }
    return SessionKey(key: currentKey, round: targetRound);
  }

  /// MD5 hash → hex string（32-char，全小写）
  ///
  /// 对齐老项目 `makeMD5(key)`，输出 32-char hex 恰好满足 AES-256 key 长度要求。
  static String _makeMd5(String input) {
    final bytes = utf8.encode(input);
    final digest = _md5Bytes(bytes);
    return digest.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
  }

  /// Minimal MD5 implementation for hash chain derivation
  static List<int> _md5Bytes(List<int> input) {
    final msgLen = input.length;
    final bitLen = msgLen * 8;
    final padded = <int>[...input, 0x80];
    while (padded.length % 64 != 56) {
      padded.add(0);
    }
    for (var i = 0; i < 8; i++) {
      padded.add((bitLen >> (i * 8)) & 0xff);
    }

    var a0 = 0x67452301;
    var b0 = 0xefcdab89;
    var c0 = 0x98badcfe;
    var d0 = 0x10325476;

    const s = [
      7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
      5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
      4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
      6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
    ];

    const k = [
      0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
      0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
      0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
      0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
      0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
      0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
      0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
      0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
      0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
      0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
      0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
      0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
      0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
      0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
      0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
      0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
    ];

    int mask32(int x) => x & 0xFFFFFFFF;
    int rotl32(int x, int n) =>
        mask32((x << n) | (mask32(x) >> (32 - n)));

    for (var offset = 0; offset < padded.length; offset += 64) {
      final m = List<int>.filled(16, 0);
      for (var j = 0; j < 16; j++) {
        final idx = offset + j * 4;
        m[j] = padded[idx] |
            (padded[idx + 1] << 8) |
            (padded[idx + 2] << 16) |
            (padded[idx + 3] << 24);
      }

      var a = a0, b = b0, c = c0, d = d0;

      for (var i = 0; i < 64; i++) {
        int f, g;
        if (i < 16) {
          f = (b & c) | (~b & d);
          g = i;
        } else if (i < 32) {
          f = (d & b) | (~d & c);
          g = (5 * i + 1) % 16;
        } else if (i < 48) {
          f = b ^ c ^ d;
          g = (3 * i + 5) % 16;
        } else {
          f = c ^ (b | ~d);
          g = (7 * i) % 16;
        }

        f = mask32(f + a + k[i] + m[g]);
        a = d;
        d = c;
        c = b;
        b = mask32(b + rotl32(f, s[i]));
      }

      a0 = mask32(a0 + a);
      b0 = mask32(b0 + b);
      c0 = mask32(c0 + c);
      d0 = mask32(d0 + d);
    }

    final result = <int>[];
    for (final val in [a0, b0, c0, d0]) {
      result.add(val & 0xff);
      result.add((val >> 8) & 0xff);
      result.add((val >> 16) & 0xff);
      result.add((val >> 24) & 0xff);
    }
    return result;
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is SessionKey && other.key == key && other.round == round;
  }

  @override
  int get hashCode => Object.hash(key, round);
}
