import { promises as fs } from 'fs';
import { join } from 'path';
import { ProjectState, BootstrapRecommendation, BootstrapAnalysis } from './types.js';

export async function analyzeProjectState(projectPath: string): Promise<ProjectState> {
  const state: ProjectState = {
    hasGitRepo: false,
    hasPackageJson: false,
    hasTests: false,
    hasDocumentation: false,
    hasCI: false,
    hasLinting: false,
    hasTypeScript: false,
    hasBuildProcess: false,
    hasReadme: false,
    hasLicense: false,
    hasGitIgnore: false,
    hasEnvironmentConfig: false,
    dependencies: [],
    devDependencies: [],
    scripts: {}
  };

  // Check for git repository
  try {
    await fs.access(join(projectPath, '.git'));
    state.hasGitRepo = true;
  } catch {}

  // Check for package.json and analyze it
  try {
    const packageJsonPath = join(projectPath, 'package.json');
    const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));
    state.hasPackageJson = true;
    state.dependencies = Object.keys(packageJson.dependencies || {});
    state.devDependencies = Object.keys(packageJson.devDependencies || {});
    state.scripts = packageJson.scripts || {};
    
    // Check for test scripts
    state.hasTests = !!(state.scripts.test && state.scripts.test !== 'echo "Error: no test specified" && exit 1');
    
    // Check for build process
    state.hasBuildProcess = !!(state.scripts.build || state.scripts.compile);
    
    // Check for linting
    state.hasLinting = state.devDependencies.some(dep => 
      dep.includes('eslint') || dep.includes('tslint') || dep.includes('prettier')
    );
    
    // Check for TypeScript
    state.hasTypeScript = state.devDependencies.includes('typescript');
  } catch {}

  // Check for documentation
  try {
    await fs.access(join(projectPath, 'docs'));
    state.hasDocumentation = true;
  } catch {}

  // Check for CI configuration
  const ciFiles = ['.github/workflows', '.circleci', '.travis.yml', 'Jenkinsfile', '.gitlab-ci.yml'];
  for (const ciFile of ciFiles) {
    try {
      await fs.access(join(projectPath, ciFile));
      state.hasCI = true;
      break;
    } catch {}
  }

  // Check for README
  try {
    await fs.access(join(projectPath, 'README.md'));
    state.hasReadme = true;
  } catch {}

  // Check for LICENSE
  try {
    await fs.access(join(projectPath, 'LICENSE'));
    state.hasLicense = true;
  } catch {}

  // Check for .gitignore
  try {
    await fs.access(join(projectPath, '.gitignore'));
    state.hasGitIgnore = true;
  } catch {}

  // Check for environment configuration
  const envFiles = ['.env.example', '.env.sample', 'config'];
  for (const envFile of envFiles) {
    try {
      await fs.access(join(projectPath, envFile));
      state.hasEnvironmentConfig = true;
      break;
    } catch {}
  }

  return state;
}

export function generateRecommendations(state: ProjectState): BootstrapRecommendation[] {
  const recommendations: BootstrapRecommendation[] = [];

  if (!state.hasGitRepo) {
    recommendations.push({
      id: 'init-git',
      title: 'Initialize Git Repository',
      description: 'Set up version control for your project',
      priority: 'high',
      category: 'setup',
      command: 'git init'
    });
  }

  if (!state.hasPackageJson) {
    recommendations.push({
      id: 'init-npm',
      title: 'Initialize NPM Package',
      description: 'Create package.json to manage dependencies',
      priority: 'high',
      category: 'setup',
      command: 'npm init -y'
    });
  }

  if (!state.hasGitIgnore) {
    recommendations.push({
      id: 'create-gitignore',
      title: 'Create .gitignore',
      description: 'Prevent committing unnecessary files',
      priority: 'high',
      category: 'setup',
      files: [{
        path: '.gitignore',
        content: `# Dependencies
node_modules/

# Build outputs
dist/
build/
*.js
*.js.map
*.d.ts

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

# Environment
.env
.env.local
.env.*.local

# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Testing
coverage/
.nyc_output/

# Misc
.atlas/
*.tmp
*.temp`,
        description: 'Standard .gitignore for Node.js projects'
      }]
    });
  }

  if (!state.hasTypeScript && state.hasPackageJson) {
    recommendations.push({
      id: 'setup-typescript',
      title: 'Set Up TypeScript',
      description: 'Add TypeScript for better type safety',
      priority: 'high',
      category: 'development',
      devDependencies: ['typescript', '@types/node'],
      scripts: {
        'build': 'tsc',
        'watch': 'tsc --watch'
      },
      files: [{
        path: 'tsconfig.json',
        content: JSON.stringify({
          compilerOptions: {
            target: 'ES2020',
            module: 'commonjs',
            lib: ['ES2020'],
            outDir: './dist',
            rootDir: './src',
            strict: true,
            esModuleInterop: true,
            skipLibCheck: true,
            forceConsistentCasingInFileNames: true,
            resolveJsonModule: true,
            declaration: true,
            declarationMap: true,
            sourceMap: true,
            removeComments: true
          },
          include: ['src/**/*'],
          exclude: ['node_modules', 'dist', '**/*.test.ts', '**/*.spec.ts']
        }, null, 2),
        description: 'TypeScript configuration'
      }]
    });
  }

  if (!state.hasTests && state.hasPackageJson) {
    recommendations.push({
      id: 'setup-testing',
      title: 'Set Up Testing Framework',
      description: 'Add Jest for unit testing with TypeScript support',
      priority: 'high',
      category: 'testing',
      devDependencies: ['jest', '@types/jest', 'ts-jest'],
      scripts: {
        'test': 'jest',
        'test:watch': 'jest --watch',
        'test:coverage': 'jest --coverage'
      },
      files: [{
        path: 'jest.config.js',
        content: `module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src'],
  testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
  collectCoverageFrom: [
    'src/**/*.ts',
    '!src/**/*.d.ts',
    '!src/**/index.ts',
    '!src/**/__tests__/**'
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80
    }
  }
};`,
        description: 'Jest configuration for TypeScript'
      }]
    });
  }

  if (!state.hasLinting && state.hasPackageJson) {
    recommendations.push({
      id: 'setup-linting',
      title: 'Set Up Code Linting',
      description: 'Add ESLint and Prettier for code quality',
      priority: 'medium',
      category: 'development',
      devDependencies: [
        'eslint',
        '@typescript-eslint/parser',
        '@typescript-eslint/eslint-plugin',
        'prettier',
        'eslint-config-prettier',
        'eslint-plugin-prettier'
      ],
      scripts: {
        'lint': 'eslint src --ext .ts',
        'lint:fix': 'eslint src --ext .ts --fix',
        'format': 'prettier --write "src/**/*.ts"'
      },
      files: [
        {
          path: '.eslintrc.json',
          content: JSON.stringify({
            parser: '@typescript-eslint/parser',
            extends: [
              'plugin:@typescript-eslint/recommended',
              'plugin:prettier/recommended'
            ],
            parserOptions: {
              ecmaVersion: 2020,
              sourceType: 'module'
            },
            rules: {
              '@typescript-eslint/explicit-function-return-type': 'off',
              '@typescript-eslint/no-explicit-any': 'warn',
              '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }]
            }
          }, null, 2),
          description: 'ESLint configuration'
        },
        {
          path: '.prettierrc',
          content: JSON.stringify({
            semi: true,
            trailingComma: 'all',
            singleQuote: true,
            printWidth: 100,
            tabWidth: 2
          }, null, 2),
          description: 'Prettier configuration'
        }
      ]
    });
  }

  if (!state.hasReadme) {
    recommendations.push({
      id: 'create-readme',
      title: 'Create README.md',
      description: 'Add project documentation',
      priority: 'medium',
      category: 'documentation',
      files: [{
        path: 'README.md',
        content: `# Project Name

## Description
Brief description of what this project does.

## Installation
\`\`\`bash
npm install
\`\`\`

## Usage
\`\`\`bash
npm start
\`\`\`

## Development
\`\`\`bash
npm run dev
\`\`\`

## Testing
\`\`\`bash
npm test
\`\`\`

## License
[LICENSE](LICENSE)`,
        description: 'Basic README template'
      }]
    });
  }

  if (!state.hasLicense) {
    recommendations.push({
      id: 'create-license',
      title: 'Add LICENSE File',
      description: 'Choose and add an appropriate license',
      priority: 'medium',
      category: 'documentation',
      files: [{
        path: 'LICENSE',
        content: `MIT License

Copyright (c) ${new Date().getFullYear()} [Your Name]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.`,
        description: 'MIT License'
      }]
    });
  }

  if (!state.hasCI && state.hasGitRepo) {
    recommendations.push({
      id: 'setup-ci',
      title: 'Set Up Continuous Integration',
      description: 'Add GitHub Actions for automated testing',
      priority: 'low',
      category: 'deployment',
      files: [{
        path: '.github/workflows/ci.yml',
        content: `name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        node-version: [18.x, 20.x]
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Use Node.js \${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: \${{ matrix.node-version }}
    
    - name: Install dependencies
      run: npm ci
    
    - name: Run linting
      run: npm run lint
    
    - name: Run tests
      run: npm test
    
    - name: Build
      run: npm run build`,
        description: 'GitHub Actions workflow'
      }]
    });
  }

  if (!state.hasEnvironmentConfig && state.hasPackageJson) {
    recommendations.push({
      id: 'setup-env-config',
      title: 'Set Up Environment Configuration',
      description: 'Add environment variable management',
      priority: 'low',
      category: 'setup',
      dependencies: ['dotenv'],
      files: [{
        path: '.env.example',
        content: `# Environment Configuration
NODE_ENV=development
PORT=3000
LOG_LEVEL=info

# Add your environment variables here
# DATABASE_URL=
# API_KEY=`,
        description: 'Example environment configuration'
      }]
    });
  }

  return recommendations;
}

export function createBootstrapAnalysis(
  projectState: ProjectState,
  recommendations: BootstrapRecommendation[]
): BootstrapAnalysis {
  const summary = {
    totalRecommendations: recommendations.length,
    highPriority: recommendations.filter(r => r.priority === 'high').length,
    mediumPriority: recommendations.filter(r => r.priority === 'medium').length,
    lowPriority: recommendations.filter(r => r.priority === 'low').length
  };

  return {
    projectState,
    recommendations,
    summary
  };
}