"""
FSRS-6 Spaced Repetition Service
Standards: FSRS-6, DSR Model, Cepeda 2006, Rule 10, Rule 28.
"""
import math
from datetime import datetime, timedelta, timezone

class FSRS:
    # FSRS-6 Default Weights (21 parameters)
    W = [
        0.212, 1.2931, 2.3065, 8.2956, 6.4133, 0.8334, 3.0194, 0.001,
        1.8722, 0.1666, 0.796, 1.4835, 0.0614, 0.2629, 1.6483, 0.6014,
        1.8729, 0.5425, 0.0912, 0.0658, 0.1542
    ]
    
    # Constants
    DECAY = -0.5
    FACTOR = 19 / 81
    REQUEST_RETENTION = 0.9

    @classmethod
    def _clamp(cls, val, min_val, max_val):
        return max(min_val, min(val, max_val))

    @classmethod
    def init_difficulty(cls, rating: int) -> float:
        """Rating: 1=Again, 2=Hard, 3=Good, 4=Easy"""
        d = cls.W[4] - (rating - 3) * cls.W[5]
        return cls._clamp(d, 1.0, 10.0)

    @classmethod
    def init_stability(cls, rating: int) -> float:
        return max(0.1, cls.W[rating - 1])

    @classmethod
    def next_interval(cls, stability: float) -> int:
        """Calculates next review date in days based on desired retention."""
        interval = (stability / cls.FACTOR) * (cls.REQUEST_RETENTION ** (1 / cls.DECAY) - 1)
        return max(1, round(interval))

    @classmethod
    def next_difficulty(cls, d: float, rating: int) -> float:
        """Updates difficulty based on review."""
        new_d = d - cls.W[6] * (rating - 3)
        # Mean reversion to prevent difficulty from drifting to extremes
        new_d = cls.W[7] * cls.init_difficulty(4) + (1 - cls.W[7]) * new_d
        return cls._clamp(new_d, 1.0, 10.0)

    @classmethod
    def next_stability(cls, d: float, s: float, r: float, rating: int) -> float:
        """Calculates new stability based on difficulty, current stability, retrievability, and rating."""
        if rating == 1:
            # Lapse (forgot)
            new_s = cls.W[11] * (d ** -cls.W[12]) * ((s + 1) ** cls.W[13] - 1) * math.exp(cls.W[14] * (1 - r))
        else:
            # Recall (remembered)
            hard_penalty = cls.W[15] if rating == 2 else 1.0
            easy_bonus = cls.W[16] if rating == 4 else 1.0
            new_s = s * (1 + math.exp(cls.W[8]) * (11 - d) * (s ** -cls.W[9]) * (math.exp((1 - r) * cls.W[10]) - 1) * hard_penalty * easy_bonus)
        
        return max(0.1, new_s)

    @classmethod
    def calculate_retrievability(cls, days_since_review: float, stability: float) -> float:
        """Calculates the probability of recall right now."""
        return (1 + cls.FACTOR * days_since_review / stability) ** cls.DECAY

def process_review(state: dict, rating: int, days_elapsed: float) -> dict:
    """
    Core function called by the pipeline.
    state: dict with keys 'difficulty', 'stability', 'reps', 'state' (NEW/LEARNING/REVIEW)
    """
    f = FSRS()
    
    if state.get('state') == 'NEW' or not state.get('stability'):
        d = f.init_difficulty(rating)
        s = f.init_stability(rating)
        reps = 1
        new_state = 'LEARNING'
    else:
        d = state['difficulty']
        s = state['stability']
        reps = state.get('reps', 0) + 1
        
        r = f.calculate_retrievability(days_elapsed, s)
        s = f.next_stability(d, s, r, rating)
        d = f.next_difficulty(d, rating)
        
        if rating == 1:
            new_state = 'RELEARNING'
        else:
            new_state = 'REVIEW'

    interval = f.next_interval(s)
    next_due = datetime.now(timezone.utc) + timedelta(days=interval)

    return {
        'difficulty': round(d, 2),
        'stability': round(s, 2),
        'reps': reps,
        'state': new_state,
        'next_due_at': next_due.isoformat(),
        'interval_days': interval
    }

def run_tests():
    """Simple internal test to verify the math works."""
    print("Running FSRS Self-Test...")
    
    # Test 1: New card graded 'Good' (3)
    state = process_review({'state': 'NEW'}, rating=3, days_elapsed=0)
    print(f"  New Card (Good) -> D:{state['difficulty']}, S:{state['stability']}, Next in: {state['interval_days']} days")
    assert state['interval_days'] >= 1
    
    # Test 2: Existing card (S=10, D=5) reviewed 10 days later with 'Good' (3)
    old_state = {'state': 'REVIEW', 'stability': 10.0, 'difficulty': 5.0, 'reps': 2}
    state2 = process_review(old_state, rating=3, days_elapsed=10)
    print(f"  Review (Good) -> D:{state2['difficulty']}, S:{state2['stability']}, Next in: {state2['interval_days']} days")
    assert state2['stability'] > 10.0 # Stability should grow
    
    print("FSRS Self-Test PASSED.")

if __name__ == '__main__':
    run_tests()
