"""
elspais.commands.init - Initialize configuration command.

Creates .elspais.toml configuration file.
"""

import argparse
from pathlib import Path
from typing import Optional


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

    Args:
        args: Parsed command line arguments

    Returns:
        Exit code (0 for success)
    """
    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)
    print(f"Created configuration: {config_path}")

    return 0


def generate_config(project_type: str, associated_prefix: Optional[str] = None) -> str:
    """Generate configuration file content."""

    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

[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]
allowed_implements = [
    "dev -> ops, prd",
    "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 '''# elspais configuration - Core Repository
# Generated by: elspais init

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

[directories]
spec = "spec"
docs = "docs"
database = "database"
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 = "-"

[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]
allowed_implements = [
    "dev -> ops, prd",
    "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"]

[validation]
hash_algorithm = "sha256"
hash_length = 8

[traceability]
output_formats = ["markdown", "html"]
scan_patterns = [
    "database/**/*.sql",
    "src/**/*.py",
    "apps/**/*.dart",
]
'''
