import { execSync } from 'child_process';
import { GitHubClient } from '../github/githubClient';
import { JiraClient } from '../jira/jiraClient';
import { FuelixClient } from '../fuelix/fuelixClient';
import * as fs from 'fs';
import * as path from 'path';
import dotenv from 'dotenv';

dotenv.config();

export class DocumentationService {
  private githubClient: GitHubClient;
  private jiraClient: JiraClient;
  private fuelixClient: FuelixClient;

  constructor(githubClient: GitHubClient, jiraClient: JiraClient, fuelixClient: FuelixClient) {
    this.githubClient = githubClient;
    this.jiraClient = jiraClient;
    this.fuelixClient = fuelixClient;
  }

  async analyzeChanges(content: string): Promise<string> {
    return await this.fuelixClient.analyzeChanges(content);
  }

  async createDocumentationPR(analysis: string): Promise<string> {
    const branchName = `docs/auto-doc-${Date.now()}`;
    
    // Create and switch to new branch
    execSync(`git checkout -b ${branchName}`);

    // Get additional information
    const commitHash = execSync('git rev-parse HEAD').toString().trim();
    const currentBranch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
    const timestamp = new Date().toISOString();

    // Create documentation file using template
    const docContent = this.generateDocumentationContent({
      analysis,
      technical_details: await this.fuelixClient.generateTechnicalDetails(analysis),
      related_components: await this.fuelixClient.identifyRelatedComponents(analysis),
      timestamp,
      branch: currentBranch,
      commit_hash: commitHash,
      additional_notes: await this.fuelixClient.generateAdditionalNotes(analysis)
    });

    // Ensure docs directory exists
    if (!fs.existsSync('docs')) {
      fs.mkdirSync('docs', { recursive: true });
    }

    // Write documentation file
    fs.writeFileSync('docs/auto-generated.md', docContent);
    
    // Commit changes
    execSync('git add docs/auto-generated.md');
    execSync('git commit -m "docs: Add auto-generated documentation"');
    execSync(`git push origin ${branchName}`);

    // Create PR using GitHub client
    return await this.githubClient.createPullRequest({
      title: "docs: Auto-generated documentation",
      body: analysis,
      branch: branchName
    });
  }

  async createJiraBacklogItem(analysis: string, prUrl?: string): Promise<void> {
    await this.jiraClient.createTicket(
      'Documentation Update',
      `Automated documentation update based on recent changes.\n\n${analysis}\n\n${prUrl ? `Related PR: ${prUrl}` : ''}`,
      process.env.JIRA_PROJECT_KEY || ''
    );
  }

  private generateDocumentationContent(data: {
    analysis: string;
    technical_details: string;
    related_components: string;
    timestamp: string;
    branch: string;
    commit_hash: string;
    additional_notes: string;
  }): string {
    const template = fs.readFileSync(path.join('docs', 'templates', 'documentation-template.md'), 'utf-8');
    
    return template
      .replace('{{analysis}}', data.analysis)
      .replace('{{technical_details}}', data.technical_details)
      .replace('{{related_components}}', data.related_components)
      .replace('{{timestamp}}', data.timestamp)
      .replace('{{branch}}', data.branch)
      .replace('{{commit_hash}}', data.commit_hash)
      .replace('{{additional_notes}}', data.additional_notes);
  }
} 