#!/usr/bin/env python3
"""
Build script for cmake-init package.

This script syncs the source files from cmake-init/ to src/cmake_init_lib/.

ARCHITECTURE:
- cmake-init/           ← Source of truth (edit these)
  ├── __init__.py
  ├── __main__.py
  ├── cmake_init.py
  ├── template.py
  └── templates/        ← All CMake project templates

- src/cmake_init_lib/   ← Generated by this script (tracked in git)
  └── [same structure]   ← Built package for distribution

WHY TWO DIRECTORIES?
- Development: Edit cmake-init/, run build.py, test with `uv run cmake-init`
- Distribution: src/ is the packaged version that gets uploaded to PyPI
- Templates are included as regular files (no ZIP compression)

WORKFLOW:
1. Edit files in cmake-init/
2. Run: python build.py
3. Test: uv run cmake-init test-project
4. Commit both cmake-init/ and src/
"""

import re
import shutil
from pathlib import Path

# Get the project root
PROJECT_ROOT = Path(__file__).parent

# Read version from SOURCE (cmake-init/), not destination (src/)
with open(PROJECT_ROOT / "cmake-init" / "__init__.py") as f:
    for line in f:
        match = re.match(r'^__version__ = "([^"]+)"$', line)
        if match is not None:
            version = match[1]
            break

print(f"Building cmake-init version {version}")

# Target directory for the package
lib_dir = PROJECT_ROOT / "src" / "cmake_init_lib"

# Create target directory if it doesn't exist
lib_dir.mkdir(parents=True, exist_ok=True)
print(f"Target directory: {lib_dir}")

# Step 1: Copy Python source files from cmake-init/ to src/cmake_init_lib/
print("Copying Python source files...")
source_files = ["__init__.py", "__main__.py", "cmake_init.py", "template.py"]
for source_file in source_files:
    src = PROJECT_ROOT / "cmake-init" / source_file
    dst = lib_dir / source_file
    if src.exists():
        shutil.copy2(src, dst)
        print(f"  Copied {source_file}")
    else:
        print(f"  Warning: {source_file} not found in cmake-init/")

# Step 2: Copy templates directory
print("Copying templates directory...")
src_templates = PROJECT_ROOT / "cmake-init" / "templates"
dst_templates = lib_dir / "templates"

# Remove existing templates directory if it exists
if dst_templates.exists():
    shutil.rmtree(dst_templates)
    print("  Removed old templates directory")

# Copy the templates directory
shutil.copytree(src_templates, dst_templates)
print(f"  Copied templates directory ({sum(1 for _ in dst_templates.rglob('*'))} files)")

print("\nBuild preparation complete!")
print("\n✅ Single source of truth: cmake-init/ directory")
