"""
Design Agent — Project Scaffolding
====================================
Creates and manages the persistent project structure.
"""

import os
import json
from datetime import datetime


def create_project(project_path: str, project_name: str) -> dict:
    """Create a new design project with the full folder structure."""
    
    dirs = [
        "brief/flows",
        "brief/_rejected",
        "architecture/screens",
        "architecture/_rejected",
        "tokens/previews",
        "tokens/_rejected",
        "components",
        "pages",
        "changelog",
    ]
    
    for d in dirs:
        os.makedirs(os.path.join(project_path, d), exist_ok=True)
    
    # Initialize project manifest
    manifest = {
        "name": project_name,
        "created": datetime.now().isoformat(),
        "current_stage": "discovery",
        "stages_completed": [],
        "version": "0.1.0",
    }
    
    manifest_path = os.path.join(project_path, "project.json")
    with open(manifest_path, 'w') as f:
        json.dump(manifest, f, indent=2)
    
    # Initialize empty component registry
    registry = {"components": [], "last_updated": datetime.now().isoformat()}
    with open(os.path.join(project_path, "components", "registry.json"), 'w') as f:
        json.dump(registry, f, indent=2)
    
    # Create first changelog entry
    log_entry = f"""# Project Created: {project_name}

**Date:** {datetime.now().strftime('%Y-%m-%d')}
**Stage:** Project initialization

New design project created. Beginning Stage 1: Discovery.
"""
    with open(os.path.join(project_path, "changelog", "000_project_created.md"), 'w') as f:
        f.write(log_entry)
    
    print(f"Created project: {project_name}")
    print(f"Location: {project_path}")
    print(f"Stage: discovery")
    
    return manifest


def advance_stage(project_path: str, new_stage: str, notes: str = "") -> dict:
    """Record completion of a stage and advance to the next."""
    manifest_path = os.path.join(project_path, "project.json")
    with open(manifest_path) as f:
        manifest = json.load(f)
    
    old_stage = manifest["current_stage"]
    manifest["stages_completed"].append({
        "stage": old_stage,
        "completed": datetime.now().isoformat(),
        "notes": notes,
    })
    manifest["current_stage"] = new_stage
    
    with open(manifest_path, 'w') as f:
        json.dump(manifest, f, indent=2)
    
    # Changelog entry
    idx = _next_changelog_index(project_path)
    log_path = os.path.join(project_path, "changelog", 
                            f"{idx:03d}_{old_stage}_completed.md")
    log_content = f"""# Stage Completed: {old_stage}

**Date:** {datetime.now().strftime('%Y-%m-%d')}
**Next stage:** {new_stage}

{notes}
"""
    with open(log_path, 'w') as f:
        f.write(log_content)
    
    return manifest


def _next_changelog_index(project_path: str) -> int:
    """Get the next available changelog index."""
    changelog_dir = os.path.join(project_path, "changelog")
    if not os.path.exists(changelog_dir):
        return 0
    existing = [f for f in os.listdir(changelog_dir) if f.endswith('.md')]
    return len(existing)


def log_decision(project_path: str, title: str, content: str):
    """Add a decision to the changelog."""
    changelog_dir = os.path.join(project_path, "changelog")
    idx = _next_changelog_index(project_path)
    
    log_path = os.path.join(changelog_dir, f"{idx:03d}_{title.lower().replace(' ', '_')}.md")
    log_content = f"""# {title}

**Date:** {datetime.now().strftime('%Y-%m-%d')}

{content}
"""
    with open(log_path, 'w') as f:
        f.write(log_content)


if __name__ == "__main__":
    import sys
    path = sys.argv[1] if len(sys.argv) > 1 else "/home/claude/test_project"
    name = sys.argv[2] if len(sys.argv) > 2 else "Untitled Project"
    create_project(path, name)
