import simpleGit, { SimpleGit } from 'simple-git';
import { mkdir, rm } from 'fs/promises';
import path from 'path';
import { env } from '../config/env.js';

export class GitService {
  private git: SimpleGit;
  private workspaceDir: string;
  private repoUrl: string;
  private token: string;

  constructor() {
    this.workspaceDir = env.GIT_WORKSPACE_DIR;
    this.repoUrl = env.GIT_REPO_URL;
    this.token = env.GIT_TOKEN;
    this.git = simpleGit();
  }

  async initialize() {
    // Ensure workspace directory exists
    await mkdir(this.workspaceDir, { recursive: true });

    // Add token to repo URL for authentication
    const authenticatedUrl = this.repoUrl.replace(
      'https://',
      `https://oauth2:${this.token}@`
    );

    try {
      // Check if repo already exists
      await this.git.cwd(this.workspaceDir);
      await this.git.status();
      console.log('Repository already exists, pulling latest...');
      await this.git.pull();
    } catch {
      // Clone if doesn't exist
      console.log('Cloning repository...');
      await rm(this.workspaceDir, { recursive: true, force: true });
      await this.git.clone(authenticatedUrl, this.workspaceDir);
      await this.git.cwd(this.workspaceDir);
    }

    // Configure git user
    await this.git.addConfig('user.name', env.GIT_USER_NAME);
    await this.git.addConfig('user.email', env.GIT_USER_EMAIL);
  }

  async commitAndPush(message: string): Promise<string> {
    await this.git.add('.');
    await this.git.commit(message);
    await this.git.push('origin', 'main');

    const log = await this.git.log({ maxCount: 1 });
    return log.latest?.hash || '';
  }

  getWorkspacePath(relativePath: string): string {
    return path.join(this.workspaceDir, relativePath);
  }

  async reset() {
    await this.git.reset(['--hard', 'HEAD']);
    await this.git.clean('f', ['-d']);
  }
}
