#!/usr/bin/env python3
"""
Generates version.json for arenasUO auto-update system.
Run this on the server whenever files are updated.

Usage:
    python generate_version.py /home/uo/download/Arenas -o /home/uo/download/Arenas/version.json
"""

import os
import sys
import json
import hashlib
import argparse
from datetime import datetime
from pathlib import Path


def compute_file_hash(filepath: Path) -> str:
    """Compute SHA256 hash of a file."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(65536), b''):
            sha256.update(chunk)
    return sha256.hexdigest()


def generate_version_info(root_path: Path, version: str = "1.0.0") -> dict:
    """Generate version info with file hashes."""
    files = {}

    # Skip these files/folders from version tracking
    skip_patterns = {
        'version.json',
        '.git',
        '__pycache__',
        '.DS_Store',
        'Thumbs.db',
        'logs',
        'notes',
    }

    for filepath in root_path.rglob('*'):
        if filepath.is_file():
            # Get relative path
            rel_path = filepath.relative_to(root_path)
            rel_path_str = str(rel_path).replace('\\', '/')

            # Skip unwanted files
            if any(skip in rel_path_str for skip in skip_patterns):
                continue

            # Skip very large files (like the zip itself)
            if filepath.suffix.lower() == '.zip':
                continue

            stat = filepath.stat()

            files[rel_path_str] = {
                "hash": compute_file_hash(filepath),
                "size": stat.st_size,
                "modified": datetime.fromtimestamp(stat.st_mtime).isoformat()
            }

            print(f"Processed: {rel_path_str}")

    return {
        "version": version,
        "lastUpdated": datetime.utcnow().isoformat(),
        "files": files
    }


def main():
    parser = argparse.ArgumentParser(description='Generate version.json for auto-update')
    parser.add_argument('path', help='Root path of game files')
    parser.add_argument('-o', '--output', default='version.json', help='Output file path')
    parser.add_argument('-v', '--version', default='1.0.0', help='Version string')
    args = parser.parse_args()

    root_path = Path(args.path)

    if not root_path.exists():
        print(f"Error: Path '{root_path}' does not exist")
        sys.exit(1)

    print(f"Generating version info for: {root_path}")
    print(f"Version: {args.version}")
    print("-" * 50)

    version_info = generate_version_info(root_path, args.version)

    output_path = Path(args.output)
    with open(output_path, 'w') as f:
        json.dump(version_info, f, indent=2)

    print("-" * 50)
    print(f"Generated version.json with {len(version_info['files'])} files")
    print(f"Output: {output_path}")


if __name__ == '__main__':
    main()
