# Implements: REQ-d00052-G
"""
elspais.commands.init - Initialize configuration command.

Creates .elspais.toml configuration file.
"""
from __future__ import annotations

import argparse
from pathlib import Path

# Example requirement template for --template flag
EXAMPLE_REQUIREMENT = """# REQ-d00001: Example Requirement Title

**Level**: Dev | **Status**: Draft | **Implements**: -

## Assertions

A. The system SHALL demonstrate the assertion format.
B. The system SHALL show proper use of SHALL language.

## Rationale

This is an example requirement demonstrating the proper format.
Delete this file after reviewing the structure.

---

**Format Notes** (delete this section):

- **Title line**: `# REQ-{type}{id}: Title` where type is p/o/d for PRD/OPS/DEV
- **Metadata line**: Level, Status, and Implements (use `-` for top-level reqs)
- **Assertions**: Labeled A-Z, each using SHALL for required behavior
- **Rationale**: Optional explanation section (non-normative)
- **Footer**: `*End* *Title* | **Hash**: XXXXXXXX` - hash computed by `elspais hash update`

Run `elspais format` for more templates and `elspais validate` to check this file.

*End* *Example Requirement Title* | **Hash**: 00000000
"""


def run(args: argparse.Namespace) -> int:
    """
    Run the init command.

    Args:
        args: Parsed command line arguments

    Returns:
        Exit code (0 for success)
    """
    # Handle --template flag separately
    if getattr(args, "template", False):
        return create_template_requirement(args)

    config_path = Path.cwd() / ".elspais.toml"

    if config_path.exists() and not args.force:
        print(f"Configuration file already exists: {config_path}")
        print("Use --force to overwrite.")
        return 1

    # Determine project type
    project_type = args.type or "core"
    associated_prefix = args.associated_prefix

    if project_type == "associated" and not associated_prefix:
        print("Error: --associated-prefix required for associated repositories")
        return 1

    # Generate configuration
    config_content = generate_config(project_type, associated_prefix)

    # Write file
    config_path.write_text(config_content, encoding="utf-8")
    print(f"Created configuration: {config_path}")

    return 0


def create_template_requirement(args: argparse.Namespace) -> int:
    """Create an example requirement file in the spec directory."""
    from elspais.config import load_config

    # Try to load config to find spec directory
    try:
        config = load_config(args.config if hasattr(args, "config") else None)
        spec_dir_name = config.get("directories", {}).get("spec", "spec")
    except Exception:
        spec_dir_name = "spec"

    spec_dir = Path.cwd() / spec_dir_name

    # Create spec directory if it doesn't exist
    if not spec_dir.exists():
        spec_dir.mkdir(parents=True)
        print(f"Created directory: {spec_dir}")

    # Create example file
    example_path = spec_dir / "EXAMPLE-requirement.md"

    if example_path.exists() and not getattr(args, "force", False):
        print(f"Example file already exists: {example_path}")
        print("Use --force to overwrite.")
        return 1

    example_path.write_text(EXAMPLE_REQUIREMENT, encoding="utf-8")
    print(f"Created example requirement: {example_path}")
    print()
    print("Next steps:")
    print("  1. Review the example to understand the format")
    print("  2. Delete or rename it when creating real requirements")
    print("  3. Run `elspais validate` to check format compliance")
    print("  4. Run `elspais hash update` to compute content hashes")

    return 0


def generate_config(project_type: str, associated_prefix: str | None = None) -> str:
    """Generate configuration file content."""
    from elspais import __version__

    if project_type == "associated":
        if associated_prefix is None:
            associated_prefix = "XXX"  # Placeholder if not provided
        return f"""# elspais configuration - Associated Repository
# Generated by: elspais init --type associated (v{__version__})
#
# Tip: Create .elspais.local.toml alongside this file for developer-local
# overrides (e.g. associate paths). It is deep-merged and gitignored.

[project]
name = "{associated_prefix.lower()}-project"
type = "associated"

[associated]
prefix = "{associated_prefix}"
id_range = [1, 99999]

[core]
# Path to core repository (relative or absolute)
path = "../core"

[directories]
spec = "spec"
docs = "docs"
code = ["src", "lib"]

[patterns]
id_template = "{{prefix}}-{{associated}}{{type}}{{id}}"
prefix = "REQ"

[patterns.types]
prd = {{ id = "p", name = "Product Requirement", level = 1 }}
ops = {{ id = "o", name = "Operations Requirement", level = 2 }}
dev = {{ id = "d", name = "Development Requirement", level = 3 }}

[patterns.id_format]
style = "numeric"
digits = 5
leading_zeros = true

[patterns.associated]
enabled = true
length = 3
format = "uppercase"
separator = "-"

[rules.hierarchy]
dev = ["dev", "ops", "prd"]
ops = ["ops", "prd"]
prd = ["prd"]
cross_repo_implements = true
allow_orphans = true  # More permissive for associated development

[rules.format]
require_hash = true
require_assertions = true
"""

    else:  # core
        return f"""# elspais configuration - Core Repository
# Generated by: elspais init (v{__version__})
#
# Tip: Create .elspais.local.toml alongside this file for developer-local
# overrides (e.g. associate paths). It is deep-merged and gitignored.

[project]
name = "my-project"
type = "core"

[directories]
spec = "spec"
docs = "docs"
code = ["src", "apps", "packages"]

[patterns]
id_template = "{{prefix}}-{{type}}{{id}}"
prefix = "REQ"

[patterns.types]
prd = {{ id = "p", name = "Product Requirement", level = 1 }}
ops = {{ id = "o", name = "Operations Requirement", level = 2 }}
dev = {{ id = "d", name = "Development Requirement", level = 3 }}

[patterns.id_format]
style = "numeric"
digits = 5
leading_zeros = true

[patterns.associated]
enabled = true
length = 3
format = "uppercase"
separator = "-"

[patterns.assertions]
label_style = "uppercase"  # "uppercase" | "numeric" | "alphanumeric" | "numeric_1based"
# max_count = 26           # Defaults to style maximum (26 for uppercase, 100 for numeric)
# zero_pad = false         # For numeric styles: "01" vs "1"

[spec]
index_file = "INDEX.md"
skip_files = ["README.md", "requirements-format.md", "INDEX.md"]

[spec.file_patterns]
"prd-*.md" = "prd"
"ops-*.md" = "ops"
"dev-*.md" = "dev"

[rules.hierarchy]
dev = ["dev", "ops", "prd"]
ops = ["ops", "prd"]
prd = ["prd"]
allow_circular = false
allow_orphans = false

[rules.format]
require_hash = true
require_rationale = false
require_assertions = true
require_status = true
allowed_statuses = ["Active", "Draft", "Deprecated", "Superseded"]

[testing]
enabled = false
test_dirs = ["tests"]
patterns = ["test_*.py", "*_test.py"]
# result_files = ["test-results.xml"]  # Uncomment to enable test result parsing
reference_keyword = "Validates"

[ignore]
# Global patterns applied everywhere
global = ["node_modules", ".git", "__pycache__", "*.pyc", ".venv", ".env"]
# Additional patterns for spec file scanning
spec = ["README.md", "INDEX.md", "drafts/**"]
# Additional patterns for code scanning
code = ["*_test.py", "conftest.py", "test_*.py"]
# Additional patterns for test scanning
test = ["fixtures/**", "__snapshots__"]
"""
