"""
CARL Scaffolding - Initialize a new CARL installation.
Creates minimal .carl/ directory structure with starter files.
"""
from pathlib import Path
from datetime import datetime


def create_carl_installation(workspace_path: str, force: bool = False) -> dict:
    """Create a new CARL installation in the given workspace.

    Creates minimal .carl/ with: manifest, global, context, commands
    No hardcoded rules - only example comments to guide users.

    Args:
        workspace_path: Path to workspace root (will create .carl/ here)
        force: If True, delete existing .carl and recreate fresh

    Returns:
        dict with success status and created paths
    """
    import shutil

    workspace = Path(workspace_path)
    carl_path = workspace / '.carl'

    if carl_path.exists():
        if force:
            # Delete existing .carl for fresh start
            shutil.rmtree(carl_path)
        else:
            return {
                'success': False,
                'error': 'CARL already exists at this location',
                'can_reinit': True  # Signal that reinit is available
            }

    try:
        # Create .carl directory
        carl_path.mkdir(parents=True, exist_ok=True)

        # Create manifest - only GLOBAL preset, ready for user-created domains
        manifest_content = f"""# CARL Manifest - Dynamic Rules Configuration
# Generated by CARL Control Panel
# Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
#
# Format:
#   {{DOMAIN}}_STATE=active|inactive
#   {{DOMAIN}}_ALWAYS_ON=true|false
#   {{DOMAIN}}_RECALL=keyword1,keyword2
#   {{DOMAIN}}_EXCLUDE=word1,word2
#
# To add a new domain:
#   1. Create a domain file (e.g., .carl/development)
#   2. Add entries below: DEVELOPMENT_STATE=active, DEVELOPMENT_RECALL=keywords
#   3. Add rules to the domain file: DEVELOPMENT_RULE_0=your rule

# ============================================================================
# DEVMODE: Debug output in responses
# ============================================================================
DEVMODE=false

# ============================================================================
# GLOBAL - Universal rules (loaded when state=active, no keyword matching)
# ============================================================================
GLOBAL_STATE=active

# ============================================================================
# CONTEXT - Token-aware context bracket rules
# ============================================================================
CONTEXT_STATE=active

# ============================================================================
# COMMANDS - Star command invocations (*brief, *discuss, etc.)
# ============================================================================
COMMANDS_STATE=active
"""
        (carl_path / 'manifest').write_text(manifest_content)

        # Create global rules file - no hardcoded rules, only examples
        global_content = f"""# GLOBAL Domain Rules
# These rules apply universally to all sessions (always_on=true).
# Generated by CARL Control Panel
# Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
#
# Format: GLOBAL_RULE_N=rule text (N starts at 0)
#
# Example rules (uncomment and customize):
# GLOBAL_RULE_0=Use absolute paths in programming to prevent path traversal issues.
# GLOBAL_RULE_1=Batch tool calls when possible, sequential only for dependencies.
# GLOBAL_RULE_2=Always validate functionality before marking tasks complete.
"""
        (carl_path / 'global').write_text(global_content)

        # Create context file - bracket-based rules for context management
        context_content = f"""# CARL Context Brackets - Token-aware behavior rules
# Generated by CARL Control Panel
# Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
#
# Context brackets trigger based on remaining token percentage:
#   FRESH: 60%+ remaining - normal operation
#   MODERATE: 40-60% remaining - reinforcing key context
#   DEPLETED: 25-40% remaining - aggressive context preservation
#   CRITICAL: <25% remaining - emergency mode
#
# Format:
#   {{BRACKET}}_RULES=true|false (enable/disable bracket)
#   {{BRACKET}}_RULE_N=rule text
#
# Example rules (uncomment and customize):

# FRESH_RULES=true
# FRESH_RULE_1=Context mode: LEAN - minimal injection overhead
# FRESH_RULE_2=Spawn fresh agents only for explicitly parallel work

# MODERATE_RULES=true
# MODERATE_RULE_1=Context mode: STANDARD - reinforcing key context
# MODERATE_RULE_2=Consider fresh agent for tasks expecting >300 lines of code

# DEPLETED_RULES=true
# DEPLETED_RULE_1=Context mode: PRESERVATION - actively managing context
# DEPLETED_RULE_2=Prefer spawning agents for any non-trivial new tasks
"""
        (carl_path / 'context').write_text(context_content)

        # Create commands file - no hardcoded commands, only examples
        commands_content = f"""# CARL Star Commands
# Explicit command invocations via *commandname in prompts.
# Generated by CARL Control Panel
# Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
#
# Format: {{COMMAND}}_RULE_N=rule text
# Usage: Type *brief, *discuss, etc. in your prompt
#
# Example commands (uncomment and customize):
#
# # *brief - Generate a session summary
# BRIEF_RULE_0=Create a concise session summary without asking for confirmation.
# BRIEF_RULE_1=Include: session goals, work completed, decisions made, next steps.
#
# # *discuss - Enter discussion mode
# DISCUSS_RULE_0=ENTER DISCUSSION MODE: Focus on understanding before proposing solutions.
# DISCUSS_RULE_1=Ask clarifying questions, explore alternatives, think out loud.
# DISCUSS_RULE_2=Do not take action or write code unless explicitly asked.
"""
        (carl_path / 'commands').write_text(commands_content)

        return {
            'success': True,
            'carl_path': str(carl_path),
            'files_created': ['manifest', 'global', 'context', 'commands']
        }

    except Exception as e:
        return {
            'success': False,
            'error': str(e)
        }


def get_suggested_workspace() -> str:
    """Get a suggested workspace path for new CARL installation."""
    home = Path.home()

    # Check common locations
    candidates = [
        home / 'chris-ai-systems',
        home / 'projects',
        home / 'workspace',
        home / 'code',
        home,
    ]

    for path in candidates:
        if path.exists() and path.is_dir():
            # Don't suggest if CARL already exists there
            if not (path / '.carl').exists():
                return str(path)

    return str(home)


def find_existing_carl_installations() -> list[dict]:
    """Find all existing .carl installations in common locations.

    Returns:
        List of dicts with 'path' and 'workspace_name' keys
    """
    home = Path.home()
    found = []

    # Check common locations where .carl might exist
    candidates = [
        home / 'chris-ai-systems',
        home / 'projects',
        home / 'workspace',
        home / 'code',
        home,
    ]

    for path in candidates:
        carl_path = path / '.carl'
        manifest_path = carl_path / 'manifest'

        if carl_path.exists() and manifest_path.exists():
            found.append({
                'path': str(path),
                'carl_path': str(carl_path),
                'workspace_name': path.name or 'home'
            })

    return found
