"""Run Command System Utility Functions

Provides helper functions for theme slug generation, path handling, etc.
"""

import time
from datetime import datetime
from pathlib import Path
from typing import List

import pypinyin
from slugify import slugify as _slugify


def generate_theme_slug(description: str, max_length: int = 90) -> str:
    """Generate theme slug (date prefix + slugified description)

    Args:
        description: original task description (should be a concise theme phrase generated by AI)
        max_length: maximum length limit (excluding date prefix)

    Returns:
        date prefix + slugified theme name (format: yyyyMMdd-slug)

    Examples:
        >>> generate_theme_slug("nano-banana-pro image api research")
        '20251203-nano-banana-pro-image-api-research'
        >>> generate_theme_slug("upwork python jobs search")
        '20251203-upwork-python-jobs-search'

    Note:
        AI should provide English theme phrases directly (3-5 words) to avoid unreadability from Chinese pinyin conversion
    """
    # Date prefix (yyyyMMdd)
    date_prefix = datetime.now().strftime("%Y%m%d")

    # Slugify directly (keep English, numbers, remove Chinese and special characters)
    slug = _slugify(description, max_length=max_length)

    # If empty (pure symbols or pure Chinese input), fallback to timestamp
    if not slug:
        slug = f"task-{int(time.time())}"

    return f"{date_prefix}-{slug}"


def is_valid_run_id(run_id: str) -> bool:
    """Validate run_id format

    Args:
        run_id: run ID to validate

    Returns:
        True if valid, False otherwise
    """
    import re

    # Support date prefix format: yyyyMMdd-slug (max 100 characters)
    pattern = r"^[a-z0-9-]{1,100}$"
    return bool(re.match(pattern, run_id))


def scan_run_directories(projects_dir: Path) -> List[str]:
    """Scan projects directory and return all run_id list

    Args:
        projects_dir: projects directory path

    Returns:
        list of run_ids (sorted by last modified time in descending order)
    """
    if not projects_dir.exists() or not projects_dir.is_dir():
        return []

    run_ids = []
    for item in projects_dir.iterdir():
        if item.is_dir() and is_valid_run_id(item.name):
            run_ids.append(item.name)

    # Sort by last modified time (most recent first)
    run_ids.sort(key=lambda rid: (projects_dir / rid).stat().st_mtime, reverse=True)

    return run_ids


def ensure_directory_exists(path: Path) -> None:
    """Ensure directory exists (create if it doesn't exist)

    Args:
        path: directory path

    Raises:
        FileSystemError: directory creation failed
    """
    from .exceptions import FileSystemError

    try:
        path.mkdir(parents=True, exist_ok=True)
    except Exception as e:
        raise FileSystemError("create directory", str(path), str(e))
