import datetime

class EvolutionMetricsTracker:
    """
    Tracks key evolution metrics for Queen AIVA to measure her evolution velocity
    towards Genesis Prime Mother status.

    Metrics tracked:
    - Stories/hour: Rate of evolution stories completed.
    - PRDs spawned/day: Rate of Product Requirement Documents generated.
    - Capability growth rate: Percentage increase in AIVA's overall capability score.
    """

    def __init__(self):
        self.initial_start_time = datetime.datetime.now(datetime.timezone.utc) # Tracks overall uptime/evolution start
        self.reset_metrics() # Initializes current period metrics

    def reset_metrics(self):
        """
        Resets the current measurement period's counters and timestamps.
        This allows for tracking metrics over specific, configurable intervals.
        """
        self.stories_completed_current_period: int = 0
        self.prds_spawned_current_period: int = 0
        self.current_period_start_time = datetime.datetime.now(datetime.timezone.utc)

        # For capability growth, we maintain a history of scores.
        self._previous_capability_score: float | None = None
        self._current_capability_score: float | None = None
        self._last_capability_update_time: datetime.datetime | None = None
        self._capability_growth_rate: float = 0.0 # Stored as a percentage

    def record_story_completion(self, count: int = 1):
        """
        Records the completion of one or more evolution stories.
        These stories represent discrete steps or milestones in AIVA's evolution.
        """
        if count < 0:
            raise ValueError("Count must be non-negative.")
        self.stories_completed_current_period += count

    def record_prd_spawn(self, count: int = 1):
        """
        Records the spawning of one or more PRDs (Product Requirement Documents).
        PRDs signify the definition of new features or capabilities for AIVA.
        """
        if count < 0:
            raise ValueError("Count must be non-negative.")
        self.prds_spawned_current_period += count

    def update_capability_score(self, new_score: float):
        """
        Updates AIVA's current capability score and calculates the growth rate.
        This score is expected to be a composite metric reflecting AIVA's overall capabilities
        and mastery, provided by an external assessment system.
        """
        if new_score < 0:
            raise ValueError("Capability score must be non-negative.")

        if self._current_capability_score is not None:
            self._previous_capability_score = self._current_capability_score

        self._current_capability_score = new_score
        self._last_capability_update_time = datetime.datetime.now(datetime.timezone.utc)

        if self._previous_capability_score is not None:
            if self._previous_capability_score == 0 and self._current_capability_score > 0:
                # Infinite growth from a zero baseline to a positive score
                self._capability_growth_rate = float('inf')
            elif self._previous_capability_score != 0:
                self._capability_growth_rate = (
                    ((self._current_capability_score - self._previous_capability_score) / self._previous_capability_score)
                    * 100.0
                )
            else:
                # Both previous and current are zero
                self._capability_growth_rate = 0.0
        else:
            # No previous score to compare against yet
            self._capability_growth_rate = 0.0

    def _get_time_elapsed_hours(self) -> float:
        """Helper to calculate hours elapsed since the current period started."""
        time_delta = datetime.datetime.now(datetime.timezone.utc) - self.current_period_start_time
        return time_delta.total_seconds() / 3600.0

    def _get_time_elapsed_days(self) -> float:
        """Helper to calculate days elapsed since the current period started."""
        time_delta = datetime.datetime.now(datetime.timezone.utc) - self.current_period_start_time
        return time_delta.total_seconds() / (3600.0 * 24.0)

    def get_stories_per_hour(self) -> float:
        """
        Calculates the average stories completed per hour during the current period.
        Returns 0.0 if no significant time has elapsed or no stories completed.
        """
        elapsed_hours = self._get_time_elapsed_hours()
        if elapsed_hours > 0.001:  # Account for very small time differences
            return self.stories_completed_current_period / elapsed_hours
        return 0.0

    def get_prds_per_day(self) -> float:
        """
        Calculates the average PRDs spawned per day during the current period.
        Returns 0.0 if no significant time has elapsed or no PRDs spawned.
        """
        elapsed_days = self._get_time_elapsed_days()
        if elapsed_days > 0.001:  # Account for very small time differences
            return self.prds_spawned_current_period / elapsed_days
        return 0.0

    def get_capability_growth_rate(self) -> float:
        """
        Returns the most recently calculated capability growth rate (as a percentage).
        """
        return self._capability_growth_rate

    def get_all_metrics(self) -> dict:
        """
        Returns a dictionary containing all currently tracked metrics for the current period.
        """
        return {
            "stories_per_hour": self.get_stories_per_hour(),
            "prds_per_day": self.get_prds_per_day(),
            "capability_growth_rate": self.get_capability_growth_rate(),
            "current_stories_completed": self.stories_completed_current_period,
            "current_prds_spawned": self.prds_spawned_current_period,
            "current_capability_score": self._current_capability_score,
            "previous_capability_score": self._previous_capability_score,
            "current_period_start_time": self.current_period_start_time.isoformat(),
            "initial_tracking_start_time": self.initial_start_time.isoformat(),
            "last_capability_update_time": self._last_capability_update_time.isoformat() if self._last_capability_update_time else None,
        }

    def __str__(self):
        """Provides a human-readable summary of the current evolution metrics."""
        metrics = self.get_all_metrics()
        cap_score_str = f"{metrics['current_capability_score']:.2f}" if metrics['current_capability_score'] is not None else 'N/A'
        prev_cap_score_str = f"{metrics['previous_capability_score']:.2f}" if metrics['previous_capability_score'] is not None else 'N/A'

        return (
            f"\n--- AIVA Evolution Metrics ---\n"
            f"  Evolution Velocity:\n"
            f"    Stories Completed/Hour: {metrics['stories_per_hour']:.4f}\n"
            f"    PRDs Spawned/Day: {metrics['prds_per_day']:.4f}\n"
            f"  Capability Growth:\n"
            f"    Current Score: {cap_score_str}\n"
            f"    Previous Score: {prev_cap_score_str}\n"
            f"    Growth Rate (since last update): {metrics['capability_growth_rate']:.4f}%\n"
            f"  Current Period Totals:\n"
            f"    Stories: {metrics['current_stories_completed']}\n"
            f"    PRDs: {metrics['current_prds_spawned']}\n"
            f"----------------------------"