package com.foxx.androidcast.entitlements;

/** Pure policy helpers (unit-tested without native I/O). */
final class EntitlementPolicy {
    /** Local entitlement blob older than this is discarded (offline abuse mitigation). */
    static final long FILE_TTL_MS = 3L * 24L * 60L * 60L * 1000L;

    /** Wall clock moved backwards beyond this vs last successful verify → treat as tamper. */
    static final long CLOCK_ROLLBACK_TOLERANCE_MS = 60_000L;

    private EntitlementPolicy() {}

    static boolean isFileStale(long fileLastModifiedMs, long nowMs, long ttlMs) {
        if (fileLastModifiedMs <= 0L) {
            return true;
        }
        long age = nowMs - fileLastModifiedMs;
        return age < 0L || age > ttlMs;
    }

    static boolean isClockRollback(long nowMs, long lastVerifiedWallMs, long toleranceMs) {
        return lastVerifiedWallMs > 0L && nowMs + toleranceMs < lastVerifiedWallMs;
    }

    static long parseKeyHex(String hex) {
        if (hex == null) {
            return 0L;
        }
        String trimmed = hex.trim();
        if (trimmed.isEmpty()) {
            return 0L;
        }
        if (trimmed.startsWith("0x") || trimmed.startsWith("0X")) {
            trimmed = trimmed.substring(2);
        }
        if (trimmed.matches("[0-9]+")) {
            try {
                return Long.parseLong(trimmed, 10);
            } catch (NumberFormatException e) {
                return 0L;
            }
        }
        try {
            return Long.parseUnsignedLong(trimmed, 16);
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    static String formatKeyHex(long key) {
        return String.format("%016x", key);
    }
}
