#!/usr/bin/env python3
"""
Generate a setup checklist for Python library projects.

Usage:
    python gen_checklist.py internal my-utils
    python gen_checklist.py public my-package
    python gen_checklist.py --help

Outputs:
    - HTML checklist (interactive) or markdown checklist
"""

import sys
from pathlib import Path
from datetime import datetime


def generate_checklist(library_type: str, library_name: str) -> str:
    """
    Generate setup checklist based on library type.
    
    Args:
        library_type: "internal" or "public"
        library_name: e.g., "my-utils"
    
    Returns:
        Markdown checklist content
    """
    if library_type not in ("internal", "public"):
        raise ValueError("library_type must be 'internal' or 'public'")
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    package_folder = library_name.replace("-", "_")
    
    checklist = f"""# Setup Checklist: {library_name}

**Type:** {library_type.capitalize()} Library  
**Generated:** {timestamp}  
**Package Folder:** `src/{package_folder}/`

---

## Phase 1: Project Structure ✓

- [ ] Directory `{library_name}/` created
- [ ] Ran `uv init --lib {library_name}`
- [ ] Structure matches:
  ```
  {library_name}/
  ├── pyproject.toml
  ├── src/
  │   └── {package_folder}/
  │       └── __init__.py
  └── README.md
  ```
- [ ] Validated structure: `python scripts/validate_structure.py .`
- [ ] All checks passed ✅

---

## Phase 2: Development Setup

- [ ] Edited `src/{package_folder}/__init__.py` with public API
- [ ] Created public API exports (`from .module import func`)
- [ ] Added `__all__` list to `__init__.py`
- [ ] Added `__version__` to `__init__.py`
- [ ] Moved code from old projects to `src/{package_folder}/`
- [ ] Created modules in `src/{package_folder}/`:
  - [ ] `module1.py`
  - [ ] `module2.py`
  - [ ] (add more as needed)
- [ ] Created `src/{package_folder}/_internal/` for private helpers
- [ ] Added docstrings to public functions
- [ ] Added type hints to public functions

---

## Phase 3: Testing (Recommended)

- [ ] Created `tests/` folder at project root
- [ ] Wrote unit tests for core functions
- [ ] All tests pass: `uv run pytest tests/`
- [ ] Test coverage documented (optional)

---

## Phase 4: Documentation

- [ ] Written `README.md` with:
  - [ ] Project description
  - [ ] Installation instructions
  - [ ] Basic usage example
  - [ ] Link to documentation (if applicable)
- [ ] Created `CHANGELOG.md` starting with version 0.1.0
- [ ] Listed all dependencies in `pyproject.toml` under `[project] dependencies`

---

## Phase 5: Git Setup

- [ ] Initialized Git: `git init`
- [ ] Created `.gitignore` with:
  - [ ] `__pycache__/`
  - [ ] `*.pyc`
  - [ ] `dist/`
  - [ ] `build/`
  - [ ] `*.egg-info/`
- [ ] All files tracked: `git add .`
- [ ] Initial commit: `git commit -m "feat: initial library setup"`
"""
    
    if library_type == "internal":
        checklist += f"""
---

## Phase 6: Internal Distribution (GitLab/GitHub)

### Setup Remote
- [ ] Created private repository on GitLab/GitHub
- [ ] Added remote: `git remote add origin git@gitlab.com:synapsis/{library_name}.git`
- [ ] Verified SSH access: `ssh -T git@gitlab.com` (works without password)
- [ ] Pushed to server: `git push -u origin main`

### Create Version Tag
- [ ] Created git tag: `git tag v0.1.0`
- [ ] Pushed tag: `git push origin v0.1.0`
- [ ] Verified tag on server: `git tag --list`

### Test Installation (Another Project)
- [ ] Create test directory: `mkdir test-install && cd test-install`
- [ ] Initialize project: `uv init`
- [ ] Install library: `uv add git+ssh://git@gitlab.com/synapsis/{library_name}.git`
- [ ] Import test: `python -c "import {package_folder}; print({package_folder}.__version__)"`
- [ ] ✅ No `ModuleNotFoundError`

### Future Updates
- [ ] Make code changes in `src/{package_folder}/`
- [ ] Update `__version__` in `__init__.py`
- [ ] Update `CHANGELOG.md`
- [ ] Commit: `git commit -m "feat: description of change"`
- [ ] Tag: `git tag vX.Y.Z`
- [ ] Push: `git push origin main && git push origin vX.Y.Z`
- [ ] Consumer projects update: `uv lock --upgrade-package {library_name}`

---

## Phase 7: Distribution Update Workflow

### When You Add a Feature
1. Edit code in `src/{package_folder}/`
2. Update version in `__init__.py`: `__version__ = "0.2.0"`
3. Update `CHANGELOG.md`
4. Commit: `git commit -m "feat: description"`
5. Tag: `git tag v0.2.0`
6. Push both: `git push origin main` and `git push origin v0.2.0`
7. Notify consumers → they run `uv lock --upgrade-package {library_name}`

### When You Fix a Bug
1. Edit code
2. Update version in `__init__.py`: `__version__ = "0.1.1"` (patch bump)
3. Update `CHANGELOG.md`
4. Commit: `git commit -m "fix: description"`
5. Tag: `git tag v0.1.1`
6. Push: `git push origin main` and `git push origin v0.1.1`
7. Consumers update automatically with `uv lock --upgrade-package {library_name}`

---

## Troubleshooting Checklist

- [ ] **ModuleNotFoundError after install?**
  - [ ] Check: src layout correct? → Run validate_structure.py
  - [ ] Check: __init__.py exists? → Verify src/{package_folder}/__init__.py present
  - [ ] Check: Package name matches? → Compare package name in pyproject.toml with folder name

- [ ] **SSH key authentication fails?**
  - [ ] Run: `ssh -T git@gitlab.com`
  - [ ] Should print: `Welcome to GitLab, @username!`
  - [ ] If fails: Add SSH key → `ssh-keygen -t ed25519` → Add public key to GitLab Settings

- [ ] **Tag not appearing in install?**
  - [ ] Check tag exists: `git tag --list`
  - [ ] Check tag pushed: `git push origin v0.1.0`
  - [ ] Consumer refresh: `uv lock --upgrade-package {library_name}`

---

## Final Verification

- [ ] Version number consistent across:
  - [ ] `src/{package_folder}/__init__.py` (`__version__`)
  - [ ] `CHANGELOG.md`
  - [ ] `git tag` (vX.Y.Z)
- [ ] README.md includes real usage example that works
- [ ] All team members can install: `uv add git+ssh://...`
- [ ] Test code passes: `uv run pytest` (if tests exist)
- [ ] No sensitive data in repo (check `.gitignore`)

**Status:** ✅ Production-ready

"""
    
    else:  # public
        checklist += f"""
---

## Phase 6: Public Distribution (PyPI)

### Account Setup (One Time)
- [ ] Created PyPI account: https://pypi.org/account/register/
- [ ] Generated API token: https://pypi.org/account/tokens/
- [ ] Saved token securely (don't commit to repo)

### Build Distribution
- [ ] Built distribution: `uv build`
- [ ] Verified artifacts in `dist/`:
  - [ ] `{library_name}-0.1.0-py3-none-any.whl`
  - [ ] `{library_name}-0.1.0.tar.gz`

### Publish to PyPI
- [ ] Created `.env` file with: `PYPI_TOKEN=pypi-AgE...` (don't commit!)
- [ ] Added `.env` to `.gitignore`
- [ ] Published: `export PYPI_TOKEN=... && uv publish --token $PYPI_TOKEN`
- [ ] Verified on PyPI: https://pypi.org/project/{library_name}/

### Test Installation (Public)
- [ ] Create test directory: `mkdir test-public && cd test-public`
- [ ] Initialize project: `uv init`
- [ ] Install from PyPI: `uv add {library_name}`
- [ ] Import test: `python -c "import {package_folder}; print({package_folder}.__version__)"`
- [ ] ✅ Works without GitHub/GitLab access

### Create Release Tag
- [ ] Tagged: `git tag v0.1.0`
- [ ] Pushed: `git push origin v0.1.0`
- [ ] Created Release on GitHub/PyPI with changelog

### Future Updates
- [ ] Make code changes in `src/{package_folder}/`
- [ ] Update `__version__` in `__init__.py`
- [ ] Update `CHANGELOG.md`
- [ ] Build: `uv build`
- [ ] Publish: `uv publish --token $PYPI_TOKEN`
- [ ] Tag: `git tag vX.Y.Z`
- [ ] Push: `git push origin main && git push origin vX.Y.Z`
- [ ] Users update: `uv upgrade {library_name}` or `uv lock --upgrade-package {library_name}`

---

## Phase 7: Release Workflow for Public Libraries

### When You Release v0.2.0
1. Edit code in `src/{package_folder}/`
2. Update version in `__init__.py`: `__version__ = "0.2.0"`
3. Update `CHANGELOG.md` with new features
4. Commit: `git commit -m "feat: add new features"`
5. Build: `uv build`
6. Publish: `uv publish --token $PYPI_TOKEN`
7. Tag: `git tag v0.2.0`
8. Push: `git push origin main && git push origin v0.2.0`
9. Create GitHub Release (optional but recommended)
10. Announce on community channels (Reddit, Twitter, etc.)

---

## Troubleshooting Checklist

- [ ] **ModuleNotFoundError after install?**
  - [ ] Same as internal (see validate_structure.py)

- [ ] **Build fails?**
  - [ ] Check `pyproject.toml` syntax: `uv build --verbose`
  - [ ] Ensure no old `setup.py` conflicts with `pyproject.toml`

- [ ] **Publish fails with authentication?**
  - [ ] Verify token is valid: `https://pypi.org/account/tokens/`
  - [ ] Token not expired? (check expiration date)
  - [ ] Using correct format: `pypi-AgE...`

- [ ] **Package version not updating on PyPI?**
  - [ ] Check version bumped in `__init__.py`
  - [ ] Check version bumped in `pyproject.toml`
  - [ ] Rebuild: `uv build`
  - [ ] Republish with new token fresh: `uv publish --token ...`

---

## Final Verification

- [ ] Version number consistent across:
  - [ ] `src/{package_folder}/__init__.py` (`__version__`)
  - [ ] `pyproject.toml` (in [project] section)
  - [ ] `CHANGELOG.md`
  - [ ] `git tag` (vX.Y.Z)
- [ ] Package installable from PyPI: `uv add {library_name}` (any machine, no git access needed)
- [ ] All tests pass: `uv run pytest`
- [ ] Documentation complete: README + changelog
- [ ] No debug code or sensitive data in source

**Status:** ✅ Published & Production-ready

"""
    
    return checklist


def main():
    if "--help" in sys.argv or len(sys.argv) < 3:
        print("""
Generate Python Library Setup Checklist

Usage:
    python gen_checklist.py internal my-utils
    python gen_checklist.py public my-package

library_type:
    internal    For proprietary Synapsis packages (Git distribution)
    public      For open-source packages (PyPI distribution)

library_name:
    Project name (e.g., my-utils, data-connector)

Examples:
    python gen_checklist.py internal synapsis-logging
    python gen_checklist.py public requests-validator
        """)
        sys.exit(0)
    
    library_type = sys.argv[1]
    library_name = sys.argv[2]
    
    try:
        checklist = generate_checklist(library_type, library_name)
        print(checklist)
        
        # Optionally save to file
        output_file = Path(f"CHECKLIST_{library_name}.md")
        output_file.write_text(checklist)
        print(f"\n💾 Checklist saved to: {output_file}\n")
        
    except ValueError as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
