"""
Sync Gherkin feature files from album/book/gherkin-samples/ to tester/features/.
"""

import shutil
from pathlib import Path
from typing import Optional


def sync_features_from_album(
    album_path: Optional[Path] = None,
    tester_path: Optional[Path] = None
) -> dict:
    """
    Sync .feature files from album/book/gherkin-samples/ to ward/tools/tester/features/.

    Args:
        album_path: Path to album/book/gherkin-samples/ (auto-detected if None)
        tester_path: Path to ward/tools/tester/features/ (auto-detected if None)

    Returns:
        Dict with sync stats: {synced: int, skipped: int, errors: int}
    """
    # Auto-detect paths if not provided
    if tester_path is None:
        tester_path = Path(__file__).parent.parent / "features"

    if album_path is None:
        # Attempt to find album in pawprint
        pawprint_root = Path(__file__).parent.parent.parent.parent
        album_path = pawprint_root / "album" / "book" / "gherkin-samples"

    # Ensure paths exist
    if not album_path.exists():
        return {
            "synced": 0,
            "skipped": 0,
            "errors": 1,
            "message": f"Album path not found: {album_path}"
        }

    tester_path.mkdir(parents=True, exist_ok=True)

    # Sync stats
    synced = 0
    skipped = 0
    errors = 0

    # Find all .feature files in album
    for feature_file in album_path.rglob("*.feature"):
        # Get relative path from album root
        relative_path = feature_file.relative_to(album_path)

        # Destination path
        dest_file = tester_path / relative_path

        try:
            # Create parent directories
            dest_file.parent.mkdir(parents=True, exist_ok=True)

            # Copy file
            shutil.copy2(feature_file, dest_file)
            synced += 1

        except Exception as e:
            errors += 1

    return {
        "synced": synced,
        "skipped": skipped,
        "errors": errors,
        "message": f"Synced {synced} feature files from {album_path}"
    }


def clean_features_dir(features_dir: Optional[Path] = None):
    """
    Clean the features directory (remove all .feature files).

    Useful before re-syncing to ensure no stale files.
    """
    if features_dir is None:
        features_dir = Path(__file__).parent.parent / "features"

    if not features_dir.exists():
        return

    # Remove all .feature files
    for feature_file in features_dir.rglob("*.feature"):
        try:
            feature_file.unlink()
        except Exception:
            pass
