import os
import zipfile
import fnmatch

def build_deployment_package():
    source_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    output_filename = os.path.join(source_dir, "nepse_cpanel_deploy.zip")
    
    # Directories and files to explicitly include
    include_patterns = [
        "app/*",
        "frontend/*",
        "nepse/*",
        "scripts/*",
        "logs/.gitkeep",  # Include logs dir but empty
        "wsgi.py",
        "passenger_wsgi.py",
        "run_wsgi.py",
        "requirements.txt",
        ".env.example",
        "start_servers.bat",
        "start_servers.py",
        "mcp_server.py", # Just in case it's needed for local tasks in cpanel
    ]
    
    # Exclude patterns to ensure clean build
    exclude_patterns = [
        "*/__pycache__/*",
        "*.pyc",
        "*/.git/*",
        "*/venv/*",
        "*/.gemini/*",
    ]

    def should_include(file_path):
        rel_path = os.path.relpath(file_path, source_dir).replace('\\', '/')
        
        # Check excludes first
        for pattern in exclude_patterns:
            if fnmatch.fnmatch(rel_path, pattern) or fnmatch.fnmatch(f"/{rel_path}", pattern):
                return False
                
        # Then check includes
        for pattern in include_patterns:
            if fnmatch.fnmatch(rel_path, pattern) or rel_path == pattern:
                return True
            # Allow contents of included directories
            if pattern.endswith("/*") and rel_path.startswith(pattern[:-2]):
                return True
                
        return False

    print(f"Building deployment package: {output_filename}")
    
    # Ensure logs dir exists for the .gitkeep
    os.makedirs(os.path.join(source_dir, "logs"), exist_ok=True)
    with open(os.path.join(source_dir, "logs", ".gitkeep"), "a") as f:
        pass

    with zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(source_dir):
            for file in files:
                file_path = os.path.join(root, file)
                if should_include(file_path):
                    arcname = os.path.relpath(file_path, source_dir)
                    zipf.write(file_path, arcname)
                    print(f"Added: {arcname}")
                    
    print("\nDeployment package built successfully!")
    print(f"File saved at: {output_filename}")

if __name__ == "__main__":
    build_deployment_package()
