#!/usr/bin/env python3
"""
Initialize a new Python library with Synapsis standards.

Usage:
    python init_library.py --name my-utils --type internal
    python init_library.py --name public-pkg --type public
    python init_library.py --help

Creates:
    - Complete src layout with __init__.py
    - pyproject.toml with proper structure
    - README.md template
    - .gitignore
    - Git initialization
"""

import sys
import argparse
import subprocess
from pathlib import Path


PYPROJECT_INTERNAL_TEMPLATE = '''[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{library_name}"
version = "0.1.0"
description = "Synapsis internal library for {library_name}"
requires-python = ">=3.8"
authors = [
    {{name = "Synapsis Team", email = "team@synapsis.id"}}
]
dependencies = [
    # Add dependencies here
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-cov>=4.0",
    "black>=22.0",
    "ruff>=0.1.0",
]

[tool.hatch.build.targets.wheel]
packages = ["src/{package_folder}"]
'''

PYPROJECT_PUBLIC_TEMPLATE = '''[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{library_name}"
version = "0.1.0"
description = "A useful Python library"
readme = "README.md"
requires-python = ">=3.8"
authors = [
    {{name = "Your Name", email = "your.email@example.com"}}
]
license = {{text = "MIT"}}
keywords = ["python", "library"]
classifiers = [
    "Development Status :: 3 - Alpha",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.8",
    "Programming Language :: Python :: 3.9",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
]
dependencies = [
    # Add dependencies here
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-cov>=4.0",
    "black>=22.0",
    "ruff>=0.1.0",
]

[project.urls]
Homepage = "https://github.com/yourusername/{library_name}"
Documentation = "https://github.com/yourusername/{library_name}"
Repository = "https://github.com/yourusername/{library_name}"

[tool.hatch.build.targets.wheel]
packages = ["src/{package_folder}"]
'''

INIT_PY_TEMPLATE = '''"""
{library_name} - Synapsis Python Library

This module provides reusable utilities for {library_name}.
"""

__version__ = "0.1.0"
__author__ = "Synapsis Team"

# Export public API
# Example:
# from .module import function_name
# __all__ = ["function_name"]

__all__ = []
'''

README_TEMPLATE = '''# {library_name}

{description}

## Installation

### For Internal (Synapsis)
```bash
uv add git+ssh://git@gitlab.com/synapsis/{library_name}.git
```

### For Public (PyPI)
```bash
uv add {library_name}
```

## Quick Start

```python
import {package_folder}

# Your code here
```

## Development

```bash
# Install with dev dependencies
uv sync --extra dev

# Run tests
uv run pytest tests/

# Format code
uv run black src/

# Lint code
uv run ruff check src/
```

## Contributing

See CHANGELOG.md for version history.

## License

MIT License (internal) or specify your license (public)
'''

GITIGNORE_TEMPLATE = '''# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
*.manifest
*.spec

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Virtual environments
venv/
env/
ENV/
env.bak/
venv.bak/
.venv/

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Project specific
.env
.env.local
*.log
'''

CHANGELOG_TEMPLATE = '''# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.1.0] - {date}

### Added
- Initial release
- Basic functionality for {library_name}

### Changed
- Nothing yet

### Fixed
- Nothing yet

### Removed
- Nothing yet
'''


def create_library(name: str, library_type: str) -> bool:
    """
    Create a new Python library with proper structure.
    
    Args:
        name: Library name (e.g., "my-utils")
        library_type: "internal" or "public"
    
    Returns:
        True if successful, False otherwise
    """
    library_path = Path(name)
    package_folder = name.replace("-", "_")
    
    # Check if directory already exists
    if library_path.exists():
        print(f"❌ Directory '{name}' already exists.")
        return False
    
    try:
        # Create directory structure
        print(f"📦 Creating library: {name}")
        library_path.mkdir(parents=True, exist_ok=True)
        
        # Create src layout
        src_path = library_path / "src" / package_folder
        src_path.mkdir(parents=True, exist_ok=True)
        print(f"   ✓ Created src/{package_folder}/")
        
        # Create __init__.py
        init_content = INIT_PY_TEMPLATE.format(
            library_name=name,
            package_folder=package_folder
        )
        (src_path / "__init__.py").write_text(init_content)
        print(f"   ✓ Created __init__.py")
        
        # Create _internal folder for private modules
        (src_path / "_internal").mkdir(exist_ok=True)
        (src_path / "_internal" / "__init__.py").write_text("# Private internal modules\n")
        print(f"   ✓ Created _internal/ folder")
        
        # Create pyproject.toml
        if library_type == "internal":
            pyproject_content = PYPROJECT_INTERNAL_TEMPLATE.format(
                library_name=name,
                package_folder=package_folder
            )
        else:
            pyproject_content = PYPROJECT_PUBLIC_TEMPLATE.format(
                library_name=name,
                package_folder=package_folder
            )
        
        (library_path / "pyproject.toml").write_text(pyproject_content)
        print(f"   ✓ Created pyproject.toml")
        
        # Create README.md
        readme_content = README_TEMPLATE.format(
            library_name=name,
            package_folder=package_folder,
            description=f"A Python library for {name}"
        )
        (library_path / "README.md").write_text(readme_content)
        print(f"   ✓ Created README.md")
        
        # Create .gitignore
        (library_path / ".gitignore").write_text(GITIGNORE_TEMPLATE)
        print(f"   ✓ Created .gitignore")
        
        # Create CHANGELOG.md
        from datetime import date
        changelog_content = CHANGELOG_TEMPLATE.format(
            date=date.today().isoformat(),
            library_name=name
        )
        (library_path / "CHANGELOG.md").write_text(changelog_content)
        print(f"   ✓ Created CHANGELOG.md")
        
        # Initialize git
        try:
            print(f"\n🔧 Initializing Git repository...")
            subprocess.run(
                ["git", "init"],
                cwd=str(library_path),
                check=True,
                capture_output=True
            )
            subprocess.run(
                ["git", "add", "."],
                cwd=str(library_path),
                check=True,
                capture_output=True
            )
            subprocess.run(
                ["git", "commit", "-m", "feat: initial library setup"],
                cwd=str(library_path),
                check=True,
                capture_output=True
            )
            print(f"   ✓ Git initialized and initial commit created")
        except subprocess.CalledProcessError as e:
            print(f"   ⚠️  Git initialization warning: {e.stderr.decode if e.stderr else 'unknown error'}")
        
        # Success message
        print(f"\n✅ Library created successfully!\n")
        print(f"📂 Location: {library_path.resolve()}")
        print(f"📦 Package: {package_folder}")
        print(f"🎯 Type: {library_type.capitalize()}\n")
        
        print(f"📋 Next steps:")
        print(f"   1. cd {name}")
        print(f"   2. Edit src/{package_folder}/__init__.py to add your API")
        print(f"   3. Create modules in src/{package_folder}/ for your code")
        print(f"   4. Edit README.md with real examples")
        
        if library_type == "internal":
            print(f"   5. Push to GitLab: git remote add origin git@gitlab.com:synapsis/{name}.git")
            print(f"   6. Create version tag: git tag v0.1.0")
            print(f"   7. Test install: uv add git+ssh://git@gitlab.com/synapsis/{name}.git")
        else:
            print(f"   5. Create PyPI account and get API token")
            print(f"   6. Build: uv build")
            print(f"   7. Publish: uv publish --token <PYPI_TOKEN>")
        
        print(f"\n💡 Use 'python gen_checklist.py {library_type} {name}' for detailed checklist\n")
        return True
        
    except Exception as e:
        print(f"❌ Error creating library: {e}")
        return False


def main():
    parser = argparse.ArgumentParser(
        description="Initialize a new Python library with Synapsis standards"
    )
    parser.add_argument(
        "--name",
        required=True,
        help="Library name (e.g., my-utils)"
    )
    parser.add_argument(
        "--type",
        choices=["internal", "public"],
        default="internal",
        help="Library type (internal for Synapsis, public for PyPI)"
    )
    
    args = parser.parse_args()
    
    success = create_library(args.name, args.type)
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()
