/**
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';

function setupHusky() {
  try {
    const huskyDir = path.resolve('.husky');
    if (!fs.existsSync(huskyDir)) {
      fs.mkdirSync(huskyDir, { recursive: true });
    }

    execSync('git config core.hooksPath .husky', { stdio: 'inherit' });

    const prePushHookPath = path.join(huskyDir, 'pre-push');
    const prePushContent = '#!/bin/sh\npnpm run verify\n';
    if (!fs.existsSync(prePushHookPath)) {
      fs.writeFileSync(prePushHookPath, prePushContent, { mode: 0o755 });
      console.log('Pre-push hook created successfully.');
    } else {
      console.log('Pre-push hook already exists.');
    }

    const commitMsgHookPath = path.join(huskyDir, 'commit-msg');
    const commitMsgContent = '#!/bin/sh\npnpm commitlint --edit "$1"\n';
    if (!fs.existsSync(commitMsgHookPath)) {
      fs.writeFileSync(commitMsgHookPath, commitMsgContent, { mode: 0o755 });
      console.log('Commit-msg hook created successfully.');
    } else {
      console.log('Commit-msg hook already exists.');
    }
  } catch (error) {
    console.error('Error setting up Husky:', error);
    process.exit(1);
  }
}

setupHusky();