//! Init command implementation
//!
//! Handles project initialization with template generation and directory
//! structure creation.

use crate::error::{CleanroomError, Result};
use crate::telemetry::cli_helpers::CliInitSpanBuilder;

/// Initialize a new test project in the current directory
pub fn init_project(force: bool, with_config: bool) -> Result<()> {
    // Get absolute project path for telemetry
    let project_path = std::env::current_dir()
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_else(|_| ".".to_string());

    // Check if already initialized
    let tests_dir = std::path::Path::new("tests");
    let scenarios_dir = std::path::Path::new("scenarios");
    let basic_test_file = tests_dir.join("basic.clnrm.toml");

    let exists_before = tests_dir.exists() && scenarios_dir.exists() && basic_test_file.exists();

    // Start telemetry span
    let span = CliInitSpanBuilder::new(project_path, exists_before, force).start();

    println!("🚀 Initializing cleanroom test project in current directory");

    if exists_before {
        if !force {
            let error = CleanroomError::validation_error("Project already initialized")
                .with_context("Use --force to reinitialize");

            span.finish(
                false,
                false,
                None,
                0,
                Some(("ConfigAlreadyExists".to_string(), error.to_string())),
            );

            return Err(error);
        }
        println!("Reinitializing existing project (--force flag used)");
    }

    // Track created files for telemetry
    let mut files_created = 0;

    // Create directory structure
    std::fs::create_dir_all(tests_dir)?;
    std::fs::create_dir_all(scenarios_dir)?;

    // Create basic test file
    let test_content = r#"# Cleanroom Test Definition
# Generated by clnrm init

[test.metadata]
name = "basic_test"
description = "Basic integration test"
timeout = "120s"

[services.test_container]
type = "generic_container"
image = "alpine:latest"

[[steps]]
name = "hello_world"
command = ["echo", "Hello from cleanroom!"]
expected_output_regex = "Hello from cleanroom!"

[[steps]]
name = "verify_environment"
command = ["uname", "-s"]
expected_output_regex = "Linux"
"#;

    std::fs::write(&basic_test_file, test_content)?;
    files_created += 1;

    let config_path = basic_test_file.to_string_lossy().to_string();

    // Create README
    let readme_content = r#"# Cleanroom Test Project

This project uses the cleanroom testing framework for hermetic integration testing.

## Quick Start

```bash
# Run tests
clnrm run tests/

# Validate configuration
clnrm validate tests/

# Show available plugins
clnrm plugins
```

## Project Structure

- `tests/` - Test definition files (.clnrm.toml)
- `scenarios/` - Test scenario definitions
- `cleanroom.toml` - Optional framework configuration
- `README.md` - This file

## Framework Self-Testing

This project demonstrates the cleanroom framework testing itself through the "eat your own dog food" principle.
"#;

    std::fs::write("README.md", readme_content)?;
    files_created += 1;

    // Create cleanroom.toml if requested
    if with_config {
        let config_content = r#"# Cleanroom Framework Configuration (optional)
# The framework works without this file - only add when customizing

[project]
name = "my-project"
version = "0.1.0"

# Uncomment to enable parallel execution
# [cli]
# parallel = true
# jobs = 4

# Uncomment to enable container reuse (10-50x faster)
# [containers]
# reuse_enabled = true
# default_image = "alpine:latest"

# See docs for all options: https://docs.cleanroom.dev/config
"#;
        std::fs::write("cleanroom.toml", config_content)?;
        files_created += 1;
        println!("✅ Project initialized successfully with configuration");
        println!("📁 Created: tests/basic.clnrm.toml, cleanroom.toml, README.md");
    } else {
        println!("✅ Project initialized successfully (zero-config)");
        println!("📁 Created: tests/basic.clnrm.toml, README.md");
    }

    // Finish telemetry span with success
    span.finish(true, true, Some(config_path), files_created, None);

    Ok(())
}
