"""
MADACE Commands - AI-Driven Agile Collaboration Engine

Implements the MADACE methodology for project planning and execution.
Based on: https://github.com/tekcin/MADACE-Method
"""

import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional

import click
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.table import Table

console = Console()


# MADACE Configuration
MADACE_CONFIG = {
    "agents": {
        "PM": {"role": "Product Manager", "focus": "Vision, priorities, acceptance"},
        "Analyst": {"role": "Business Analyst", "focus": "Requirements, user stories"},
        "Architect": {"role": "Solution Architect", "focus": "Design, patterns, specs"},
        "SM": {"role": "Scrum Master", "focus": "Workflow, state machine, tracking"},
        "Developer": {"role": "Developer", "focus": "Implementation, testing, docs"},
    },
    "states": ["BACKLOG", "TODO", "IN_PROGRESS", "DONE"],
    "complexity_criteria": [
        "scope",
        "dependencies",
        "technical_complexity",
        "team_size",
        "time_constraints",
        "innovation",
        "integration",
        "maintenance",
    ],
    "workflow_levels": {
        1: {"name": "Simple", "min_score": 0, "max_score": 8},
        2: {"name": "Moderate", "min_score": 9, "max_score": 16},
        3: {"name": "Complex", "min_score": 17, "max_score": 24},
        4: {"name": "Very High", "min_score": 25, "max_score": 32},
    },
}


@click.group()
def madace():
    """MADACE - Methodology for AI-Driven Agile Collaboration Engine"""
    pass


@madace.command()
@click.option("--path", type=click.Path(exists=True), help="Project path")
def init(path: Optional[str]):
    """
    Initialize MADACE for a project

    Creates .madace/ directory with configuration and backlog.
    """
    project_path = Path(path) if path else Path.cwd()
    madace_dir = project_path / ".madace"

    try:
        console.print()
        console.print(
            Panel.fit(
                "[bold cyan]Initializing MADACE[/bold cyan]\n\n"
                "[yellow]Creating MADACE directory structure...[/yellow]",
                title="[bold]MADACE Setup[/bold]",
                border_style="cyan",
            )
        )

        # Create directories
        madace_dir.mkdir(exist_ok=True)
        (madace_dir / "stories").mkdir(exist_ok=True)
        (madace_dir / "milestones").mkdir(exist_ok=True)
        (madace_dir / "logs").mkdir(exist_ok=True)

        # Create config file
        config_file = madace_dir / "madace.json"
        if not config_file.exists():
            config = {
                "project": {
                    "name": project_path.name,
                    "path": str(project_path),
                    "initialized": datetime.now().isoformat(),
                },
                "agents": MADACE_CONFIG["agents"],
                "states": MADACE_CONFIG["states"],
                "complexity": {"score": 0, "level": 0, "criteria": {}},
                "current_todo": None,
                "current_in_progress": None,
            }
            config_file.write_text(json.dumps(config, indent=2))

        # Create empty backlog
        backlog_file = madace_dir / "BACKLOG.md"
        if not backlog_file.exists():
            backlog_file.write_text(
                "# MADACE Backlog\n\n"
                "**Project**: {}\n\n".format(project_path.name)
                + "**State Machine**: BACKLOG → TODO → IN_PROGRESS → DONE\n\n"
                + "**Rules**:\n"
                + "- Maximum 1 story in TODO\n"
                + "- Maximum 1 story in IN_PROGRESS\n"
                + "- No state skipping\n\n"
                + "---\n\n"
                + "## Stories\n\n"
                + "_No stories yet. Use `groknroll madace story add` to create stories._\n"
            )

        console.print()
        console.print(
            Panel.fit(
                "[bold green]✓ MADACE initialized![/bold green]\n\n"
                f"[cyan]Directory:[/cyan] {madace_dir}\n"
                "[cyan]Config:[/cyan] madace.json\n"
                "[cyan]Backlog:[/cyan] BACKLOG.md\n\n"
                "[dim]Next: Run complexity assessment[/dim]\n"
                "[dim]  groknroll madace assess[/dim]",
                title="[bold]Setup Complete[/bold]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)


@madace.command()
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--interactive", is_flag=True, help="Interactive assessment")
def assess(path: Optional[str], interactive: bool):
    """
    Assess project complexity using MADACE criteria

    Calculates complexity score (0-32) and workflow level (1-4).
    """
    project_path = Path(path) if path else Path.cwd()
    madace_dir = project_path / ".madace"
    config_file = madace_dir / "madace.json"

    if not config_file.exists():
        console.print(
            "[bold red]Error:[/bold red] MADACE not initialized. Run 'groknroll madace init' first."
        )
        sys.exit(1)

    try:
        console.print()
        console.print(
            Panel.fit(
                "[bold cyan]MADACE Complexity Assessment[/bold cyan]\n\n"
                "[yellow]8 criteria, 0-4 points each (max 32 points)[/yellow]",
                title="[bold]Assessment[/bold]",
                border_style="cyan",
            )
        )

        # Load config
        config = json.loads(config_file.read_text())

        # Criteria assessment
        criteria_scores = {}
        total_score = 0

        if interactive:
            console.print("\n[bold]Rate each criterion (0-4):[/bold]\n")
            for criterion in MADACE_CONFIG["complexity_criteria"]:
                score = click.prompt(
                    f"  {criterion.replace('_', ' ').title()}", type=int, default=0
                )
                score = max(0, min(4, score))  # Clamp 0-4
                criteria_scores[criterion] = score
                total_score += score
        else:
            # Auto-assess based on project (simplified)
            console.print("\n[dim]Auto-assessing based on project...[/dim]\n")

            # Count files, dependencies, etc.
            py_files = list(project_path.rglob("*.py"))
            total_lines = sum(
                len(f.read_text().splitlines()) for f in py_files if f.is_file()
            )

            # Simple heuristics
            criteria_scores = {
                "scope": min(4, len(py_files) // 10),
                "dependencies": 2,  # Default medium
                "technical_complexity": min(4, total_lines // 1000),
                "team_size": 1,  # Solo by default
                "time_constraints": 2,
                "innovation": 2,
                "integration": 2,
                "maintenance": 2,
            }
            total_score = sum(criteria_scores.values())

        # Determine workflow level
        workflow_level = 1
        for level, info in MADACE_CONFIG["workflow_levels"].items():
            if info["min_score"] <= total_score <= info["max_score"]:
                workflow_level = level
                break

        # Update config
        config["complexity"] = {
            "score": total_score,
            "level": workflow_level,
            "criteria": criteria_scores,
            "assessed_at": datetime.now().isoformat(),
        }
        config_file.write_text(json.dumps(config, indent=2))

        # Display results
        table = Table(title="Complexity Breakdown", show_header=True)
        table.add_column("Criterion", style="cyan")
        table.add_column("Score", justify="right", style="green")

        for criterion, score in criteria_scores.items():
            table.add_row(criterion.replace("_", " ").title(), f"{score}/4")

        console.print()
        console.print(table)

        percentage = (total_score / 32) * 100
        level_name = MADACE_CONFIG["workflow_levels"][workflow_level]["name"]

        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]Total Score:[/bold cyan] {total_score}/32 ({percentage:.0f}%)\n"
                f"[bold cyan]Workflow Level:[/bold cyan] {workflow_level} - {level_name}\n\n"
                "[dim]This determines planning depth and agent involvement.[/dim]",
                title="[bold green]✓ Assessment Complete[/bold green]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)


@madace.command()
@click.option("--path", type=click.Path(exists=True), help="Project path")
def status(path: Optional[str]):
    """
    Show MADACE project status

    Displays current state, stories in progress, and metrics.
    """
    project_path = Path(path) if path else Path.cwd()
    madace_dir = project_path / ".madace"
    config_file = madace_dir / "madace.json"

    if not config_file.exists():
        console.print(
            "[bold red]Error:[/bold red] MADACE not initialized. Run 'groknroll madace init' first."
        )
        sys.exit(1)

    try:
        config = json.loads(config_file.read_text())

        # Project info
        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]Project:[/bold cyan] {config['project']['name']}\n"
                f"[cyan]Path:[/cyan] {config['project']['path']}\n"
                f"[cyan]Initialized:[/cyan] {config['project']['initialized'][:10]}",
                title="[bold]MADACE Project[/bold]",
                border_style="cyan",
            )
        )

        # Complexity
        complexity = config.get("complexity", {})
        if complexity.get("score"):
            level_info = MADACE_CONFIG["workflow_levels"][complexity["level"]]
            console.print()
            console.print(
                Panel.fit(
                    f"[bold cyan]Score:[/bold cyan] {complexity['score']}/32\n"
                    f"[cyan]Level:[/cyan] {complexity['level']} - {level_info['name']}",
                    title="[bold]Complexity[/bold]",
                    border_style="yellow",
                )
            )

        # Current work
        console.print()
        current_todo = config.get("current_todo") or "[dim]None[/dim]"
        current_in_progress = config.get("current_in_progress") or "[dim]None[/dim]"

        console.print(
            Panel.fit(
                f"[bold cyan]TODO:[/bold cyan] {current_todo}\n"
                f"[bold cyan]IN_PROGRESS:[/bold cyan] {current_in_progress}",
                title="[bold]Current State[/bold]",
                border_style="green",
            )
        )

        # State machine rules
        console.print()
        console.print("[bold]State Machine:[/bold] BACKLOG → TODO → IN_PROGRESS → DONE")
        console.print("[dim]Rules: Max 1 TODO, Max 1 IN_PROGRESS, No skipping[/dim]")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@madace.group()
def story():
    """Manage MADACE user stories"""
    pass


@story.command()
@click.argument("title")
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--points", type=int, help="Story points (Fibonacci: 1,2,3,5,8,13)")
@click.option("--milestone", help="Milestone name")
def add(title: str, path: Optional[str], points: Optional[int], milestone: Optional[str]):
    """
    Add a new user story to backlog

    Stories are created in BACKLOG state by default.
    """
    project_path = Path(path) if path else Path.cwd()
    madace_dir = project_path / ".madace"
    backlog_file = madace_dir / "BACKLOG.md"

    if not backlog_file.exists():
        console.print(
            "[bold red]Error:[/bold red] MADACE not initialized. Run 'groknroll madace init' first."
        )
        sys.exit(1)

    try:
        # Generate story ID
        existing = backlog_file.read_text()
        import re

        story_ids = re.findall(r"## Story (\d+\.\d+\.\d+):", existing)
        if story_ids:
            last_id = story_ids[-1]
            parts = last_id.split(".")
            new_id = f"{parts[0]}.{parts[1]}.{int(parts[2]) + 1}"
        else:
            new_id = "1.1.1"

        # Story template
        story_points = points if points else 3
        story_milestone = milestone if milestone else "M1"

        story = (
            f"\n## Story {new_id}: {title}\n\n"
            "**State**: BACKLOG\n\n"
            "**As a**: developer\n"
            f"**I want**: {title.lower()}\n"
            "**So that**: [benefit here]\n\n"
            "**Acceptance Criteria**:\n"
            "- [ ] [Criterion 1]\n"
            "- [ ] [Criterion 2]\n"
            "- [ ] [Criterion 3]\n\n"
            "**Technical Notes**:\n"
            "```python\n"
            "# Implementation notes\n"
            "```\n\n"
            "**Dependencies**: None\n\n"
            f"**Points**: {story_points}\n\n"
            f"**Milestone**: {story_milestone}\n\n"
            "---\n"
        )

        # Append to backlog
        with open(backlog_file, "a") as f:
            f.write(story)

        console.print()
        console.print(
            Panel.fit(
                f"[bold green]✓ Story created![/bold green]\n\n"
                f"[cyan]ID:[/cyan] {new_id}\n"
                f"[cyan]Title:[/cyan] {title}\n"
                f"[cyan]Points:[/cyan] {story_points}\n"
                f"[cyan]State:[/cyan] BACKLOG\n\n"
                f"[dim]Edit in: {backlog_file}[/dim]",
                title="[bold]Story Added[/bold]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)


@story.command()
@click.argument("story_id")
@click.argument("new_state", type=click.Choice(["TODO", "IN_PROGRESS", "DONE"]))
@click.option("--path", type=click.Path(exists=True), help="Project path")
def move(story_id: str, new_state: str, path: Optional[str]):
    """
    Move story to new state (enforces state machine rules)

    State transitions: BACKLOG → TODO → IN_PROGRESS → DONE
    """
    project_path = Path(path) if path else Path.cwd()
    madace_dir = project_path / ".madace"
    backlog_file = madace_dir / "BACKLOG.md"
    config_file = madace_dir / "madace.json"

    if not backlog_file.exists() or not config_file.exists():
        console.print("[bold red]Error:[/bold red] MADACE not initialized.")
        sys.exit(1)

    try:
        # Load config
        config = json.loads(config_file.read_text())

        # Enforce state machine rules
        if new_state == "TODO" and config.get("current_todo"):
            console.print(
                f"[bold red]Error:[/bold red] Story {config['current_todo']} "
                "is already in TODO. Maximum 1 story allowed."
            )
            sys.exit(1)

        if new_state == "IN_PROGRESS" and config.get("current_in_progress"):
            console.print(
                f"[bold red]Error:[/bold red] Story {config['current_in_progress']} "
                "is already IN_PROGRESS. Maximum 1 story allowed."
            )
            sys.exit(1)

        # Update backlog file
        content = backlog_file.read_text()
        import re

        # Find the story header and state line (may be on different lines)
        story_pattern = rf"## Story {re.escape(story_id)}:"
        if not re.search(story_pattern, content):
            console.print(f"[bold red]Error:[/bold red] Story {story_id} not found.")
            sys.exit(1)

        # Find and replace the state line
        state_pattern = rf"(\*\*State\*\*: )(BACKLOG|TODO|IN_PROGRESS|DONE)"

        # Find the story section first
        story_start = content.find(f"## Story {story_id}:")
        if story_start == -1:
            console.print(f"[bold red]Error:[/bold red] Story {story_id} not found.")
            sys.exit(1)

        # Find next story or end of file
        next_story_start = content.find("\n## Story ", story_start + 1)
        story_end = next_story_start if next_story_start != -1 else len(content)

        # Extract story section
        story_section = content[story_start:story_end]

        # Replace state in story section
        updated_section = re.sub(state_pattern, rf"\1{new_state}", story_section, count=1)

        # Replace in full content
        content = content[:story_start] + updated_section + content[story_end:]
        backlog_file.write_text(content)

        # Update config
        if new_state == "TODO":
            config["current_todo"] = story_id
        elif new_state == "IN_PROGRESS":
            config["current_in_progress"] = story_id
            config["current_todo"] = None  # Clear TODO
        elif new_state == "DONE":
            if config.get("current_in_progress") == story_id:
                config["current_in_progress"] = None

        config_file.write_text(json.dumps(config, indent=2))

        console.print()
        console.print(
            Panel.fit(
                f"[bold green]✓ Story moved![/bold green]\n\n"
                f"[cyan]Story:[/cyan] {story_id}\n"
                f"[cyan]State:[/cyan] {new_state}\n\n"
                "[dim]State machine enforced ✓[/dim]",
                title="[bold]State Updated[/bold]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)


@madace.command()
@click.option("--path", type=click.Path(exists=True), help="Project path")
def agents(path: Optional[str]):
    """
    Show MADACE agent roles and responsibilities
    """
    console.print()
    console.print(
        Panel.fit(
            "[bold cyan]C.O.R.E. System[/bold cyan]\n\n"
            "[yellow]C[/yellow]ollaboration - Human-AI partnership\n"
            "[yellow]O[/yellow]ptimized - Refined agile process\n"
            "[yellow]R[/yellow]eflection - Guided thinking\n"
            "[yellow]E[/yellow]ngine - Orchestrating framework",
            title="[bold]MADACE Principles[/bold]",
            border_style="cyan",
        )
    )

    # Agent table
    table = Table(title="\nMADACE Agents", show_header=True)
    table.add_column("Agent", style="cyan", width=12)
    table.add_column("Role", style="green", width=20)
    table.add_column("Focus", style="yellow")

    for agent_id, agent_info in MADACE_CONFIG["agents"].items():
        table.add_row(agent_id, agent_info["role"], agent_info["focus"])

    console.print(table)

    console.print("\n[bold]Workflow Phases:[/bold]")
    console.print("1. [cyan]Analysis[/cyan] - PM + Analyst define requirements")
    console.print("2. [cyan]Planning[/cyan] - Architect designs solution")
    console.print("3. [cyan]Solutioning[/cyan] - Detailed design specs")
    console.print("4. [cyan]Implementation[/cyan] - Developer builds + tests")
    console.print()


if __name__ == "__main__":
    madace()
