import { containsCyrillic, transliterate } from "./transliterate";

// export const transformLinks = (html: string): string => {
//     if (!html) return html;

//     // Regex to match specific domain links, excluding wp-content
//     // Now also captures the full URL to handle different parts
//     const regex = /(https?:\/\/)?(www\.)?new\.jkhsakha\.ru\/(?!wp-content)([^\s"']*)/g;

//     return html.replace(regex, (match, protocol, www, path) => {
//         // Extract the full path including leading slash
//         let fullPath = path;

//         // Make sure path starts with /
//         if (!fullPath.startsWith('/')) {
//             fullPath = '/' + fullPath;
//         }

//         fullPath = decodeURIComponent(fullPath)

//         // Check if the path contains Cyrillic characters
//         if (containsCyrillic(fullPath)) {
//             console.log("contains Cyrillic, transliterating:", fullPath);
//             // Split the path into segments
//             const pathSegments = fullPath.split('/').filter((segment: any) => segment.length > 0);

//             // Transliterate each segment that contains Cyrillic
//             const transliteratedSegments = pathSegments.map((segment: any) => {
//                 return containsCyrillic(segment) ? transliterate(segment) : segment;
//             });

//             // Reconstruct the path
//             const transliteratedPath = '/' + transliteratedSegments.join('/');

//             // Ensure the path ends with trailing slash if original had it
//             if (fullPath.endsWith('/') && !transliteratedPath.endsWith('/')) {
//                 return transliteratedPath + '/';
//             }

//             return transliteratedPath;
//         }

//         // If no Cyrillic, return the original path
//         return fullPath;
//     });
// };

export const transformLinks = (html: string): string => {
    if (!html) return html;

    // First, replace wp-content/uploads links with storage URL
    const wpContentRegex = /(https?:\/\/)?(www\.)?new\.jkhsakha\.ru\/wp-content\/uploads\/([^\s"']*)/g;

    html = html.replace(wpContentRegex, (match, protocol, www, path) => {
        const storageUrl = process.env.NEXT_PUBLIC_STORAGE_URL?.replace(/\/$/, ''); // Remove trailing slash if exists
        if (!storageUrl) {
            console.warn('NEXT_PUBLIC_STORAGE_URL is not defined');
            return match; // Return original if env var not set
        }

        // Decode and process the path for Cyrillic characters
        let fullPath = '/' + decodeURIComponent(path);

        if (containsCyrillic(fullPath)) {
            console.log("contains Cyrillic, transliterating:", fullPath);
            const pathSegments = fullPath.split('/').filter((segment: any) => segment.length > 0);

            const transliteratedSegments = pathSegments.map((segment: any) => {
                return containsCyrillic(segment) ? transliterate(segment) : segment;
            });

            fullPath = '/' + transliteratedSegments.join('/');

            if (path.endsWith('/') && !fullPath.endsWith('/')) {
                fullPath += '/';
            }
        }

        return `${storageUrl}${fullPath}`;
    });

    // Then handle other domain links (excluding wp-content)
    const otherLinksRegex = /(https?:\/\/)?(www\.)?new\.jkhsakha\.ru\/(?!wp-content)([^\s"']*)/g;

    return html.replace(otherLinksRegex, (match, protocol, www, path) => {
        let fullPath = path;

        if (!fullPath.startsWith('/')) {
            fullPath = '/' + fullPath;
        }

        fullPath = decodeURIComponent(fullPath);

        if (containsCyrillic(fullPath)) {
            console.log("contains Cyrillic, transliterating:", fullPath);
            const pathSegments = fullPath.split('/').filter((segment: any) => segment.length > 0);

            const transliteratedSegments = pathSegments.map((segment: any) => {
                return containsCyrillic(segment) ? transliterate(segment) : segment;
            });

            const transliteratedPath = '/' + transliteratedSegments.join('/');

            if (fullPath.endsWith('/') && !transliteratedPath.endsWith('/')) {
                return transliteratedPath + '/';
            }

            return transliteratedPath;
        }

        return fullPath;
    });
};


export function toRelativePath(input: string): string {
    try {
        // Handles absolute URLs
        const url = new URL(input);
        return url.pathname + url.search + url.hash;
    } catch {
        // Already relative (or invalid URL)
        if (input.startsWith('/')) return input;
        return '/' + input;
    }
}

const extractPathFromUrl = (url: string): string => {
    try {
        const urlObject = new URL(url);
        return urlObject.pathname;
    } catch {
        // If URL parsing fails, return the original string
        return url;
    }
};
