"""
Version Helper Utility

Reads and parses the VERSION file to provide version information to all test modules.
"""
from pathlib import Path
from typing import Optional, Tuple
from dataclasses import dataclass


@dataclass
class VersionInfo:
    """Parsed version information"""
    full_version: str
    major: int
    minor: int
    patch: int
    build: int
    timestamp: Optional[str] = None


class VersionHelper:
    """Helper class for reading and managing version information"""
    
    def __init__(self, project_dir: str):
        self.project_dir = Path(project_dir)
        self.version_file = self.project_dir / "VERSION"
        self._cached_version: Optional[VersionInfo] = None
    
    def read_version(self) -> VersionInfo:
        """Read and parse the VERSION file"""
        if self._cached_version:
            return self._cached_version
        
        if not self.version_file.exists():
            # Create default version if file doesn't exist
            default_version = "0.0.0.0"
            with open(self.version_file, 'w') as f:
                f.write(default_version + "\n")
                f.write("1970-01-01 00:00:00\n")
            return self._parse_version(default_version, None)
        
        try:
            with open(self.version_file, 'r') as f:
                lines = f.readlines()
            
            version_line = lines[0].strip() if lines else "0.0.0.0"
            timestamp = lines[1].strip() if len(lines) > 1 else None
            
            self._cached_version = self._parse_version(version_line, timestamp)
            return self._cached_version
        except Exception as e:
            # Return default version on error
            return self._parse_version("0.0.0.0", None)
    
    def _parse_version(self, version_str: str, timestamp: Optional[str]) -> VersionInfo:
        """Parse version string into components"""
        try:
            parts = version_str.split('.')
            if len(parts) >= 4:
                major = int(parts[0])
                minor = int(parts[1])
                patch = int(parts[2])
                build = int(parts[3])
            else:
                # Default to 0.0.0.0 if format is invalid
                major, minor, patch, build = 0, 0, 0, 0
        except (ValueError, IndexError):
            # Default to 0.0.0.0 if parsing fails
            major, minor, patch, build = 0, 0, 0, 0
        
        return VersionInfo(
            full_version=version_str,
            major=major,
            minor=minor,
            patch=patch,
            build=build,
            timestamp=timestamp
        )
    
    def get_version_string(self) -> str:
        """Get the full version string"""
        return self.read_version().full_version
    
    def get_version_tuple(self) -> Tuple[int, int, int, int]:
        """Get version as tuple (major, minor, patch, build)"""
        version = self.read_version()
        return (version.major, version.minor, version.patch, version.build)
    
    def format_version_header(self) -> str:
        """Format version for header display"""
        version = self.read_version()
        if version.timestamp:
            return f"v{version.full_version} ({version.timestamp})"
        return f"v{version.full_version}"
