/**
 * GitFlow Branch — Name normalization, type detection, validation.
 * Self-contained: imports only from local lib.
 */

import type { BranchType, GitFlowConfig } from './types.js';
import { execGit } from './git.js';

export function normalizeBranchName(input: string, maxLength = 50): string {
  return input
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .replace(/[ _']/g, '-')
    .replace(/[^a-z0-9-]/g, '')
    .replace(/-{2,}/g, '-')
    .replace(/^-/, '')
    .replace(/-$/, '')
    .slice(0, maxLength)
    .replace(/-$/, '');
}

export function detectBranchType(branchName: string): BranchType {
  if (branchName === 'main' || branchName === 'master') return 'main';
  if (branchName === 'develop' || branchName === 'development') return 'develop';
  if (branchName.startsWith('feature/')) return 'feature';
  if (branchName.startsWith('release/')) return 'release';
  if (branchName.startsWith('hotfix/')) return 'hotfix';
  return 'other';
}

export function getBaseBranch(branchType: BranchType, config: GitFlowConfig): string {
  switch (branchType) {
    case 'feature': return config.git.branches.develop;
    case 'release':
    case 'hotfix': return config.git.branches.main;
    default: return config.git.branches.develop;
  }
}

export function getTargetBranch(branchType: BranchType, config: GitFlowConfig): string {
  switch (branchType) {
    case 'feature': return config.git.branches.develop;
    case 'release':
    case 'hotfix': return config.git.branches.main;
    default: return config.git.branches.develop;
  }
}

export function buildFullBranchName(name: string, branchType: BranchType, config: GitFlowConfig): string {
  const prefix = config.git.prefixes[branchType as keyof typeof config.git.prefixes];
  if (!prefix) return name;
  return `${prefix}${name}`;
}

export function stripPrefix(fullBranch: string): string {
  return fullBranch.replace(/^(feature|release|hotfix)\//, '');
}

export async function branchExists(branch: string, remote = false, cwd?: string): Promise<boolean> {
  if (remote) {
    const result = await execGit(['ls-remote', '--heads', 'origin', branch], cwd);
    return result.stdout.length > 0;
  }
  const result = await execGit(['rev-parse', '--verify', branch], cwd);
  return result.exitCode === 0;
}

export function validateBranchName(name: string): { valid: boolean; error?: string } {
  if (!name || name.trim().length === 0) {
    return { valid: false, error: 'Branch name cannot be empty' };
  }
  if (name.length > 100) {
    return { valid: false, error: 'Branch name too long (max 100 characters)' };
  }
  if (/[~^:?*\[\\]/.test(name)) {
    return { valid: false, error: `Branch name contains invalid characters: ${name}` };
  }
  if (name.startsWith('-') || name.endsWith('.') || name.endsWith('/') || name.includes('..')) {
    return { valid: false, error: `Branch name has invalid format: ${name}` };
  }
  return { valid: true };
}
