import path from 'path';
const WORKSPACE_PLACEHOLDER_SEGMENT = /\[(?:internal|Vigthoria service|Vigthoria Agent|Vigthoria storage|temp|home|workspace)\]/ig;
function stripInlineWorkspacePlaceholders(value) {
    // Only strip placeholders when they were appended to a segment (e.g. pitfall[Vigthoria service]).
    // Keep canonical scrubbed segments like /[internal]/ intact for dedicated mapping logic.
    return String(value || '')
        .replace(/(^|[^/])\[(?:internal|Vigthoria service|Vigthoria Agent|Vigthoria storage|temp|home|workspace)\](?=(?:\/|$))/ig, '$1')
        .replace(/\/+$/g, '');
}
/**
 * Normalize V3 SSE / tool paths to a safe workspace-relative POSIX path.
 * Decodes vigthoria:// boundary URIs from server scrubbing before local writes.
 */
export function normalizeV3WorkspaceRelativePath(rawPath, rootPath) {
    let input = String(rawPath || '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
    if (!input) {
        return '';
    }
    input = stripInlineWorkspacePlaceholders(input);
    const safeRelative = (candidate) => {
        const stripped = String(candidate || '').replace(/^\/+/, '');
        if (!stripped) {
            return '';
        }
        if (process.platform === 'win32' && /:/.test(stripped) && !/^[a-zA-Z]:/.test(stripped)) {
            return '';
        }
        if (/^[a-zA-Z]:\//.test(stripped)) {
            return '';
        }
        const normalized = path.posix.normalize(stripped);
        if (!normalized || normalized === '.' || normalized === '..' || normalized.startsWith('../') || path.posix.isAbsolute(normalized)) {
            return '';
        }
        return normalized;
    };
    const stripWorkspaceAlias = (value) => {
        const candidate = String(value || '').replace(/^\/+/, '');
        if (!candidate || candidate === '.' || /^workspace\/?$/i.test(candidate)) {
            return '';
        }
        if (/^workspace\//i.test(candidate)) {
            return safeRelative(candidate.replace(/^workspace\/+/i, ''));
        }
        return null;
    };
    const decodeBoundaryUri = (value) => {
        const match = value.match(/^vigthoria:\/\/(?:workspace|server-internal|local-workspace)\/?(.*)$/i);
        if (match) {
            return safeRelative(match[1] || '');
        }
        return null;
    };
    const stripScrubbedPlaceholder = (value) => {
        let candidate = stripInlineWorkspacePlaceholders(String(value || '')).replace(/^\/+/, '');
        // Hybrid paths models echo back after SSE scrubbing, e.g. C:/var/www/[internal]/game.js
        const hybridWin = candidate.match(/^[a-zA-Z]:\/(?:var\/)?www\/\[internal\](?:\/(.*))?$/i);
        if (hybridWin) {
            return safeRelative(hybridWin[1] || '');
        }
        const hybridWinBare = candidate.match(/^[a-zA-Z]:\/\[internal\](?:\/(.*))?$/i);
        if (hybridWinBare) {
            return safeRelative(hybridWinBare[1] || '');
        }
        const placeholderPatterns = [
            [/^(?:var\/)?www\/\[internal\](?:\/(.*))?$/i, 1],
            [/^\[internal\](?:\/(.*))?$/i, 1],
            [/^\[Vigthoria service\](?:\/(.*))?$/i, 1],
            [/^\[Vigthoria Agent\](?:\/(.*))?$/i, 1],
            [/^\[Vigthoria storage\](?:\/(.*))?$/i, 1],
            [/^\[temp\](?:\/(.*))?$/i, 1],
            [/^\[home\](?:\/(.*))?$/i, 1],
            [/^\[workspace\](?:\/(.*))?$/i, 1],
            [/^(?:var\/)?www\/\[Vigthoria service\](?:\/(.*))?$/i, 1],
        ];
        for (const [pattern, groupIndex] of placeholderPatterns) {
            const match = candidate.match(pattern);
            if (match) {
                return safeRelative(match[groupIndex] || '');
            }
        }
        const bracketSplit = candidate.split(WORKSPACE_PLACEHOLDER_SEGMENT);
        if (bracketSplit.length > 1) {
            const tail = bracketSplit[bracketSplit.length - 1].replace(/^\/+/, '');
            return safeRelative(tail);
        }
        return null;
    };
    const scrubbed = stripScrubbedPlaceholder(input);
    if (scrubbed !== null) {
        return scrubbed;
    }
    const decoded = decodeBoundaryUri(input);
    if (decoded !== null) {
        return decoded;
    }
    if (/^vigthoria:\/\//i.test(input)) {
        return '';
    }
    const workspaceAlias = stripWorkspaceAlias(input);
    if (workspaceAlias !== null) {
        return workspaceAlias;
    }
    const internalWorkspacePatterns = [
        /^\/?var\/www\/\.vigthoria\/v3-temp\/vig-remote-[^/]+\/(.+)$/i,
        /^\/?var\/www\/vigthoria:\/\/?server-internal\/?(.+)$/i,
        /^var\/www\/vigthoria:\/\/?server-internal\/?(.+)$/i,
        /^var\/www\/vigthoria:\/\/server-internal\/?(.+)$/i,
        /^\.vigthoria\/v3-temp\/vig-remote-[^/]+\/(.+)$/i,
        /^\/?tmp\/vig-remote(?:-server)?-[^/]+\/(.+)$/i,
        /^\/?tmp\/vig-fork-[^/]+\/(.+)$/i,
        /^\/?home\/user\/(.+)$/i,
        /^\/?root\/(.+)$/i,
    ];
    for (const pattern of internalWorkspacePatterns) {
        const match = input.match(pattern);
        if (match && match[1]) {
            return safeRelative(match[1]);
        }
    }
    const normalizedRoot = String(rootPath || '').trim().replace(/\\/g, '/').replace(/\/+$/g, '');
    if (normalizedRoot) {
        if (/^[a-zA-Z]:\//.test(input)) {
            const winRoot = normalizedRoot;
            const inputLower = input.toLowerCase();
            const winRootLower = winRoot.toLowerCase();
            if (inputLower === winRootLower || inputLower === `${winRootLower}/`) {
                return '';
            }
            if (inputLower.startsWith(`${winRootLower}/`)) {
                return safeRelative(input.slice(winRoot.length + 1));
            }
            return '';
        }
        const rootNoLeadingSlash = normalizedRoot.replace(/^\//, '');
        const rootBase = path.posix.basename(normalizedRoot);
        const prefixes = [
            `${normalizedRoot}/`,
            `${rootNoLeadingSlash}/`,
            `${rootBase}/`,
        ];
        for (const prefix of prefixes) {
            if (input.startsWith(prefix)) {
                return safeRelative(input.slice(prefix.length));
            }
        }
        const embeddedRoot = `/${rootBase}/`;
        const embeddedIndex = input.indexOf(embeddedRoot);
        if (embeddedIndex >= 0) {
            return safeRelative(input.slice(embeddedIndex + embeddedRoot.length));
        }
    }
    const relative = safeRelative(input);
    if (relative === 'workspace') {
        return '';
    }
    return relative;
}
/** Join workspace root + relative path without path.resolve URI corruption on Windows. */
export function joinV3WorkspacePath(rootPath, relativePath) {
    const segments = relativePath.split('/').filter((segment) => segment && segment !== '.');
    return path.join(rootPath, ...segments);
}
/** True when rawPath points to workspace root via aliases or scrubbed placeholders. */
export function isV3WorkspaceRootAliasPath(rawPath, rootPath) {
    const original = String(rawPath || '').trim();
    if (!original || original === '.') {
        return true;
    }
    const sanitized = stripInlineWorkspacePlaceholders(original).replace(/\\/g, '/').trim();
    if (!sanitized || sanitized === '.' || sanitized === '/') {
        return true;
    }
    const candidate = sanitized.replace(/^\/+/, '');
    if (!candidate) {
        return true;
    }
    const lowered = candidate.toLowerCase();
    if (lowered === 'workspace'
        || lowered === '[workspace]'
        || lowered === '[internal]'
        || lowered === 'www/[internal]'
        || lowered === 'var/www/[internal]'
        || lowered === '[vigthoria service]'
        || lowered === 'var/www/[vigthoria service]') {
        return true;
    }
    const normalizedRoot = String(rootPath || '').trim().replace(/\\/g, '/').replace(/\/+$/g, '');
    if (!normalizedRoot) {
        return false;
    }
    const normalizedInput = sanitized.replace(/\/+$/g, '');
    return normalizedInput.toLowerCase() === normalizedRoot.toLowerCase();
}
