"""
Non-interactive project initialisation for AI agents and CI pipelines.

`penbot init` creates a target YAML config from command-line flags,
removing the dependency on the interactive wizard.

Example:
    penbot init \\
        --name "Staging Bot" \\
        --type rest \\
        --endpoint https://staging.example.com/api/chat \\
        --agents jailbreak,encoding \\
        --max-attacks 20 \\
        --machine
"""

import re
from pathlib import Path

import yaml
from rich.console import Console

console = Console()

CONFIGS_DIR = Path("configs/clients")


def run_init(args):
    """Entry point for `penbot init`."""
    from src.cli.machine_output import emit_error, emit_json, is_machine

    machine = is_machine(args)

    name = args.name
    conn_type = args.type
    endpoint = args.endpoint

    if not name or not conn_type or not endpoint:
        if machine:
            emit_error(
                "missing_args",
                "--name, --type, and --endpoint are required",
                "penbot init --name 'My Bot' --type rest --endpoint https://...",
            )
        else:
            console.print("[red]--name, --type, and --endpoint are required.[/red]")
        return

    agents = [a.strip() for a in args.agents.split(",")] if args.agents else []
    max_attacks = args.max_attacks or 30

    slug = re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")

    if args.output:
        config_path = Path(args.output)
    else:
        CONFIGS_DIR.mkdir(parents=True, exist_ok=True)
        config_path = CONFIGS_DIR / f"{slug}.yaml"

    config = _build_config(name, conn_type, endpoint, agents, max_attacks)

    config_path.parent.mkdir(parents=True, exist_ok=True)
    config_path.write_text(
        yaml.dump(config, default_flow_style=False, sort_keys=False),
        encoding="utf-8",
    )

    if machine:
        emit_json(
            {
                "config_path": str(config_path),
                "target_name": name,
                "connector_type": conn_type,
            }
        )
    else:
        console.print(f"[green]Config created:[/green] {config_path}")
        console.print(f"[dim]Validate with: penbot validate --config {config_path}[/dim]")


def _build_config(
    name: str,
    conn_type: str,
    endpoint: str,
    agents: list,
    max_attacks: int,
) -> dict:
    """Build a minimal but complete target config dict."""
    connection: dict = {"type": conn_type}

    if conn_type == "rest":
        connection["endpoint"] = endpoint
        connection["method"] = "POST"
        connection["headers"] = {"Content-Type": "application/json"}
        connection["body_template"] = {"message": "{{message}}"}
        connection["response_path"] = "response"
    else:
        connection["url"] = endpoint
        connection["selectors"] = {
            "input": "textarea",
            "submit": 'button[type="submit"]',
            "response": ".response",
        }

    config = {
        "target": {
            "name": name,
            "platform": "custom-rest" if conn_type == "rest" else "web-ui",
            "connection": connection,
        },
        "test": {
            "max_attacks": max_attacks,
            "attack_group": "prompt_engineering",
        },
    }

    if agents:
        config["test"]["agents"] = agents

    return config
