import boto3
from botocore.exceptions import ClientError
from datetime import datetime, timezone
from .config import AWS_REGION, CLAIMS_TABLE
from .retry import with_retry
from .exceptions import PersistenceError

_dynamodb = boto3.resource("dynamodb", region_name=AWS_REGION)
_table = _dynamodb.Table(CLAIMS_TABLE)

@with_retry(max_attempts=4, base_delay=0.25, max_delay=1.5)
def update_claim_status(claim_id: str, new_status: str) -> None:
    """
    Update the claim's status and timestamp in DynamoDB with retry on transient errors.
    Raises PersistenceError if the final attempt fails.
    """
    now_iso = datetime.now(timezone.utc).isoformat()
    try:
        _table.update_item(
            Key={"claimId": claim_id},
            UpdateExpression="SET #S = :s, updatedAt = :u",
            ExpressionAttributeNames={"#S": "status"},
            ExpressionAttributeValues={":s": new_status, ":u": now_iso},
        )
    except ClientError as e:
        raise PersistenceError(f"Failed to update status for {claim_id}: {e}")