import os
import hashlib
import json
from pathlib import Path
from .exceptions import PFXValidationError

def calculate_checksum(data: str) -> str:
    """Calculate MD5 checksum for data"""
    return hashlib.md5(data.encode('utf-8')).hexdigest()

def validate_pfx(file_path: str) -> bool:
    """Validate a PFX file structure"""
    try:
        with open(file_path, 'r') as f:
            content = f.read()

        # Basic validation checks
        if "# PandaFlex" not in content:
            raise PFXValidationError("Missing PandaFlex header")

        if "[Schema]" not in content or "[Data]" not in content:
            raise PFXValidationError("Missing required sections")

        return True
    except Exception as e:
        raise PFXValidationError(f"Validation failed: {str(e)}")

def generate_example(output_dir: str = ".", filename: str = "example.pfx"):
    """Generate an example PFX file"""
    example_content = """# PandaFlex v1.0
# Metadata: {"created": "2023-11-15", "description": "Example PandaFlex file"}

[Schema]
id: int32
name: str
value: float64
is_valid: bool
categories: list[str]
attributes: dict

[Data]
# Sample data
1, "Product A", 19.99, true, ["electronics", "gadgets"], {"weight": 0.5, "color": "black"}
2, "Product B", 29.99, false, ["home", "furniture"], {"weight": 5.2, "color": "brown"}
3, "Product C", 9.99, true, ["office", "supplies"], {"weight": 0.1, "color": "white"}

[Footer]
row_count: 3
compression: none
checksum: "example_checksum"
"""

    output_path = os.path.join(output_dir, filename)
    with open(output_path, 'w') as f:
        f.write(example_content)

    return output_path