import typer
import os
import json
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn

app = typer.Typer(help="PlatformSistemas Senior Agent CLI - War Room Engine")
console = Console()

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = BASE_DIR

def load_json(filename):
    path = os.path.join(DATA_DIR, filename)
    if not os.path.exists(path):
        return None
    with open(path, 'r', encoding='utf-8') as f:
        return json.load(f)

@app.command()
def context(topic: str = typer.Argument("general", help="Topic to get context for (api, database, context)")):
    """Retrieve structured project context from JSON data stores."""
    data = load_json(f"{topic}.json")
    if not data:
        console.print(f"[red]Context for '{topic}' not found.[/red]")
        return
    
    console.print(Panel(f"Project Context: [bold cyan]{topic.upper()}[/bold cyan]", border_style="blue"))
    console.print_json(data=data)

from rules.technical_rules import audit_file

@app.command()
def audit(path: str = typer.Argument(".", help="Path or file to audit")):
    """Perform technical audit following 'War Room' rules (CSS Fluidity, 14KB, etc)."""
    console.print(f"[yellow]Auditing:[/yellow] {path}")
    
    files_to_audit = []
    if os.path.isfile(path):
        files_to_audit.append(path)
    else:
        for root, _, files in os.walk(path):
            if any(x in root for x in ['node_modules', '.git', 'dist', 'build']):
                continue
            for f in files:
                if f.endswith(('.html', '.css', '.js', '.jsx')):
                    files_to_audit.append(os.path.join(root, f))

    table = Table(title="Audit Results")
    table.add_column("File", style="white")
    table.add_column("Rule", style="cyan")
    table.add_column("Status")
    table.add_column("Details")
    
    for file_path in files_to_audit:
        results = audit_file(file_path)
        rel_path = os.path.relpath(file_path, os.getcwd())
        for r in results:
            status = "[green]✅ PASS[/green]" if r['passed'] else "[red]❌ FAIL[/red]"
            table.add_row(rel_path, r['rule'], status, r['details'])
    
    console.print(table)

@app.command()
def create(type: str, name: str, ambient: str = "workspace"):
    """Create a new component, service, or hook."""
    console.print(f"[cyan]Creating {type}:[/cyan] [bold]{name}[/bold] in [bold]{ambient}[/bold]")
    
    # Path mappings based on project structure
    paths = {
        "component": f"src/features/{ambient}/components/{name}.jsx",
        "service": f"src/features/{ambient}/{name}Service.js",
        "hook": f"src/features/{ambient}/hooks/use{name}.js"
    }
    
    if type not in paths:
        console.print(f"[red]Invalid type. Use: component, service, hook.[/red]")
        return
    
    target_path = os.path.join(os.getcwd(), paths[type])
    os.makedirs(os.path.dirname(target_path), exist_ok=True)
    
    # Template generation (simplified)
    template = f"// New {type} created by Senior Agent\nexport const {name} = () => {{}};"
    
    with open(target_path, 'w', encoding='utf-8') as f:
        f.write(template)
        
    console.print(f"[green]Successfully created at:[/green] {target_path}")

@app.command()
def register(feature: str, status: str = "active"):
    """Register a new feature or change in the project history."""
    history = load_json("history.json") or []
    history.append({
        "feature": feature,
        "status": status,
        "timestamp": "2026-02-08" # Should be dynamic
    })
    
    with open(os.path.join(DATA_DIR, "history.json"), 'w', encoding='utf-8') as f:
        json.dump(history, f, indent=2)
    
    console.print(f"[green]Registered feature:[/green] {feature}")

if __name__ == "__main__":
    app()
