import logging
import subprocess
from pathlib import Path
from datetime import datetime
from typing import Optional

logger = logging.getLogger(__name__)

class PakManager:
    
    def __init__(self, config_manager):
        self.config_manager = config_manager
        self.repak_path = Path("tools/repak/repak.exe")
        self.aes_key = "0x33A604DF49A07FFD4A4C919962161F5C35A134D37EFA98DB37A34F6450D7D386"
    
    def extract_base_pak(self) -> bool:
        config = self.config_manager.get_app_config()
        game_path = Path(config.get('game_base_path', ''))
        
        if not game_path.exists():
            logger.error("Game path not set")
            return False
        
        pak_file = game_path / "Stalker2" / "Content" / "Paks" / "pakchunk0-Windows.pak"
        
        if not pak_file.exists():
            logger.error(f"PAK file not found: {pak_file}")
            return False
        
        timestamp = datetime.now().strftime("%d-%m-%Y_%H-%M-%S")
        extract_dir = Path("data/extract") / f"pakchunk0-Windows_{timestamp}"
        extract_dir.mkdir(parents=True, exist_ok=True)
        
        logger.info(f"Extracting {pak_file} to {extract_dir}")
        print(f"\nExtracting game files...")
        print(f"File: pakchunk0-Windows.pak")
        print(f"Output: {extract_dir}")
        print()
        
        try:
            cmd = [
                str(self.repak_path),
                "--aes-key", self.aes_key,
                "unpack",
                str(pak_file),
                "--output", str(extract_dir)
            ]
            
            result = subprocess.run(cmd, text=True)
            
            print()
            
            if result.returncode == 0:
                logger.info("Extraction completed successfully")
                print("✓ Extraction completed successfully!")
                
                self.config_manager.update_app_config({
                    'last_extraction': timestamp,
                    'last_extraction_path': str(extract_dir)
                })
                
                return True
            else:
                logger.error(f"Extraction failed with return code: {result.returncode}")
                print(f"✗ Extraction failed!")
                return False
                
        except Exception as e:
            logger.error(f"Extraction error: {e}")
            print(f"✗ Extraction error: {e}")
            return False
    
    def pack_mod(self, input_dir: Path, output_file: Path) -> bool:
        logger.info(f"Packing {input_dir} to {output_file}")
        print(f"Packing mod: {output_file.name}")
        print()
        
        try:
            cmd = [
                str(self.repak_path),
                "pack",
                "--version", "V11",
                str(input_dir),
                str(output_file)
            ]
            
            result = subprocess.run(cmd, text=True)
            
            print()
            
            if result.returncode == 0:
                logger.info("Packing completed successfully")
                return True
            else:
                logger.error(f"Packing failed with return code: {result.returncode}")
                print(f"✗ Packing failed!")
                return False
                
        except Exception as e:
            logger.error(f"Packing error: {e}")
            print(f"✗ Packing error: {e}")
            return False
    
    def get_latest_extraction(self) -> Optional[Path]:
        config = self.config_manager.get_app_config()
        
        if 'last_extraction_path' in config:
            path = Path(config['last_extraction_path'])
            if path.exists():
                return path
        
        extract_dir = Path("data/extract")
        if extract_dir.exists():
            extractions = []
            for item in extract_dir.iterdir():
                if item.is_dir() and 'pakchunk' in item.name.lower():
                    try:
                        extractions.append((item.stat().st_mtime, item))
                    except:
                        extractions.append((0, item))
            
            if extractions:
                extractions.sort(key=lambda x: x[0], reverse=True)
                latest_path = extractions[0][1]
                print(f"Using extraction folder: {latest_path.name}")
                return latest_path
        
        return None