// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "../RWAStorage.sol";

/**
 * @title RWAUriCodec
 * @notice Canonical URI hashing for IPFS, Filecoin, Arweave, HTTPS, internal refs.
 */
library RWAUriCodec {
    error RWAUriCodec_invalidUri(string uri);

    function uriHash(string memory uri) internal pure returns (bytes32) {
        bytes memory b = bytes(uri);
        if (b.length == 0) revert RWAUriCodec_invalidUri(uri);
        return keccak256(b);
    }

    function detectScheme(string memory uri) internal pure returns (RWAStorage.UriScheme) {
        bytes memory b = bytes(uri);
        if (b.length < 7) return RWAStorage.UriScheme.None;
        if (_startsWith(b, "ipfs://")) return RWAStorage.UriScheme.IPFS;
        if (_startsWith(b, "filecoin://")) return RWAStorage.UriScheme.Filecoin;
        if (_startsWith(b, "ar://") || _startsWith(b, "arweave://")) {
            return RWAStorage.UriScheme.Arweave;
        }
        if (_startsWith(b, "https://")) return RWAStorage.UriScheme.HTTPS;
        if (_startsWith(b, "dbis://")) return RWAStorage.UriScheme.InternalDB;
        return RWAStorage.UriScheme.None;
    }

    function _startsWith(bytes memory data, string memory prefix) private pure returns (bool) {
        bytes memory p = bytes(prefix);
        if (data.length < p.length) return false;
        for (uint256 i = 0; i < p.length; i++) {
            if (data[i] != p[i]) return false;
        }
        return true;
    }
}
