"""Update command implementation for MakePython."""

from __future__ import annotations

import re
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING

from ...interfaces.command import CommandResult, CommandType, ValidatableCommand

if TYPE_CHECKING:
    from ...core.context import ExecutionContext


class UpdateCommand(ValidatableCommand):
    """Update build dates in __init__.py files."""

    name = "update"
    alias = "u"
    description = "Update build dates in __init__.py files"
    command_type = CommandType.UTIL

    def validate(self, context: ExecutionContext) -> bool:
        """Validate update command prerequisites.

        Args:
            context: Execution context

        Returns
        -------
            True if validation passes, False otherwise
        """
        # Check if pyproject.toml exists
        pyproject_path = context.cwd / "pyproject.toml"
        if not pyproject_path.exists():
            self.logger.warning("pyproject.toml not found, but will continue")

        return True

    def _update_init_file(self, init_path: Path) -> bool:
        """Update build date in __init__.py file.

        Args:
            init_path: Path to __init__.py file

        Returns
        -------
            True if updated, False otherwise
        """
        try:
            if not init_path.exists():
                return False

            content = init_path.read_text(encoding="utf-8")

            # Look for common date patterns
            today = datetime.now().strftime("%Y-%m-%d")
            year = datetime.now().year

            # Patterns to match
            patterns = [
                (r'__date__\s*=\s*["\'].*?["\']', f'__date__ = "{today}"'),
                (r'__build_date__\s*=\s*["\'].*?["\']', f'__build_date__ = "{today}"'),
                (r'BUILD_DATE\s*=\s*["\'].*?["\']', f'BUILD_DATE = "{today}"'),
                (r'__copyright__\s*=\s*["\'].*?["\']', f'__copyright__ = "{year}"'),
            ]

            updated = False
            new_content = content

            for pattern, replacement in patterns:
                if re.search(pattern, new_content):
                    new_content = re.sub(pattern, replacement, new_content)
                    updated = True
                    self.logger.debug(f"Updated {init_path}: {replacement}")

            if updated:
                init_path.write_text(new_content, encoding="utf-8")
                self.logger.info(f"Updated {init_path}")
                return True

            return False

        except Exception as e:
            self.logger.error(f"Failed to update {init_path}: {e}")
            return False

    def execute(self, context: ExecutionContext) -> CommandResult:
        """Execute update command.

        Args:
            context: Execution context

        Returns
        -------
            CommandResult with execution status
        """
        if not self.validate(context):
            return CommandResult(success=False, message="Validation failed")

        self.logger.info("Updating build dates...")

        root_dir = context.project_root or context.cwd
        updated_count = 0

        # Find all __init__.py files
        for init_file in root_dir.rglob("__init__.py"):
            # Skip common directories that shouldn't be updated
            if any(skip in str(init_file.parent) for skip in [".venv", "venv", "__pycache__", ".git"]):
                continue

            if self._update_init_file(init_file):
                updated_count += 1

        if updated_count > 0:
            self.logger.info(f"Updated {updated_count} file(s)")
            return CommandResult(success=True, message=f"Updated {updated_count} file(s)")
        self.logger.info("No files needed updating")
        return CommandResult(success=True, message="No files needed updating")
