/**
 * GitFlow Cross-Platform Path Normalization.
 * Self-contained: only uses node built-ins.
 */

import { relative, resolve } from 'path';
import type { Platform } from './types.js';

export function normalizeForPlatform(inputPath: string, platform: Platform): string {
  if (!inputPath) return inputPath;

  if (platform === 'wsl') {
    const winDriveMatch = inputPath.match(/^([A-Za-z]):[/\\](.*)/);
    if (winDriveMatch) {
      const drive = winDriveMatch[1].toLowerCase();
      const rest = winDriveMatch[2].replace(/\\/g, '/');
      return `/mnt/${drive}/${rest}`;
    }
    return inputPath;
  }

  const wslMatch = inputPath.match(/^\/mnt\/([a-z])\/(.*)/);
  if (wslMatch) {
    const drive = wslMatch[1].toUpperCase();
    return `${drive}:/${wslMatch[2]}`;
  }

  return inputPath.replace(/\\/g, '/');
}

export function normalizeForStorage(inputPath: string): string {
  if (!inputPath) return inputPath;

  const wslMatch = inputPath.match(/^\/mnt\/([a-z])\/(.*)/);
  if (wslMatch) {
    const drive = wslMatch[1].toUpperCase();
    return `${drive}:/${wslMatch[2]}`;
  }

  const winMatch = inputPath.match(/^([A-Za-z]):[/\\](.*)/);
  if (winMatch) {
    return `${winMatch[1].toUpperCase()}:/${winMatch[2].replace(/\\/g, '/')}`;
  }

  return inputPath;
}

export function toForwardSlashes(p: string): string {
  return p.replace(/\\/g, '/');
}

export function relativePath(from: string, to: string): string {
  return toForwardSlashes(relative(resolve(from), resolve(to)));
}
