#!/usr/bin/env python3
"""
Validate Python library structure compliance with Synapsis standards.

Usage:
    python validate_structure.py /path/to/library
    python validate_structure.py .

Checks:
    - src layout (not flat)
    - __init__.py existence
    - pyproject.toml correctness
    - Package name consistency (underscores in folder match snake_case)
"""

import sys
from pathlib import Path


def validate_library_structure(library_path: str) -> bool:
    """
    Validate library structure against Synapsis standards.
    
    Returns:
        True if all checks pass, False otherwise.
    """
    path = Path(library_path).resolve()
    
    if not path.exists():
        print(f"❌ Library path does not exist: {path}")
        return False
    
    issues = []
    warnings = []
    
    # Check 1: pyproject.toml exists
    pyproject = path / "pyproject.toml"
    if not pyproject.exists():
        issues.append("pyproject.toml not found in root")
        return False
    
    # Parse pyproject.toml to get package name
    package_name = extract_package_name(pyproject)
    if not package_name:
        issues.append("Could not extract package name from pyproject.toml [project] name field")
        return False
    
    package_folder_name = package_name.replace("-", "_")
    
    # Check 2: src folder exists
    src = path / "src"
    if not src.exists():
        issues.append("src/ folder not found")
    elif not src.is_dir():
        issues.append("src/ exists but is not a directory")
        return False
    
    # Check 3: src/package_name folder exists
    pkg_dir = src / package_folder_name
    if not pkg_dir.exists():
        issues.append(
            f"src/{package_folder_name}/ not found\n"
            f"   Expected: src/{package_folder_name}/ (matching package name '{package_name}')"
        )
    elif not pkg_dir.is_dir():
        issues.append(f"src/{package_folder_name} exists but is not a directory")
        return False
    
    # Check 4: __init__.py exists in package folder
    init_file = pkg_dir / "__init__.py"
    if not init_file.exists():
        issues.append(f"__init__.py not found in src/{package_folder_name}/")
    else:
        # Bonus: Check if __init__.py exports anything
        init_content = init_file.read_text()
        if "__all__" not in init_content and not any(
            line.startswith("from ") or line.startswith("import ")
            for line in init_content.split("\n")
        ):
            warnings.append(
                f"src/{package_folder_name}/__init__.py is empty\n"
                f"   → Consider exporting public API with 'from .module import func' and '__all__'"
            )
    
    # Check 5: git initialized
    git_dir = path / ".git"
    if not git_dir.exists():
        warnings.append("Git repository not initialized. Run: git init")
    
    # Check 6: Check for common anti-patterns
    # Flat layout check
    if (path / f"{package_folder_name}.py").exists():
        issues.append(
            f"⚠️  Flat layout detected: {package_folder_name}.py exists at root\n"
            f"   → Move code to src/{package_folder_name}/ (src layout)"
        )
    
    # Check 7: .gitignore present
    gitignore = path / ".gitignore"
    if not gitignore.exists():
        warnings.append(".gitignore not found. Consider creating one.")
    else:
        gitignore_content = gitignore.read_text()
        required_ignores = ["__pycache__", "*.pyc", "dist", "build", ".egg-info"]
        missing = [ig for ig in required_ignores if ig not in gitignore_content]
        if missing:
            warnings.append(
                f".gitignore missing entries: {', '.join(missing)}"
            )
    
    # Print results
    print(f"\n📦 Validating: {path}\n")
    
    if issues:
        print("❌ ISSUES (must fix):")
        for issue in issues:
            print(f"   • {issue}")
        print()
    
    if warnings:
        print("⚠️  WARNINGS (recommended fixes):")
        for warning in warnings:
            print(f"   • {warning}")
        print()
    
    if not issues and not warnings:
        print("✅ All checks passed! Library structure is compliant.\n")
        return True
    
    if issues:
        return False
    
    return True


def extract_package_name(pyproject_path: Path) -> str | None:
    """
    Extract package name from pyproject.toml [project] name field.
    
    Returns:
        Package name (e.g., "my-utils") or None if not found.
    """
    try:
        content = pyproject_path.read_text()
        for line in content.split("\n"):
            if line.strip().startswith("name"):
                # Extract value from: name = "package-name"
                parts = line.split("=", 1)
                if len(parts) == 2:
                    value = parts[1].strip().strip('"\'')
                    return value
    except Exception as e:
        print(f"Error parsing pyproject.toml: {e}")
    
    return None


if __name__ == "__main__":
    library_path = sys.argv[1] if len(sys.argv) > 1 else "."
    
    success = validate_library_structure(library_path)
    sys.exit(0 if success else 1)
