#!/usr/bin/env python3
"""
Tool to verify Stripe subscription implementation.

Checks that Stripe integration follows best practices for:
- Webhook signature verification
- Subscription status handling
- Customer portal integration
- Plan/feature gating

Usage:
    python -m stablestack.tools.check_stripe_subscriptions /path/to/project
    python -m stablestack.tools.check_stripe_subscriptions --verbose
"""

import argparse
import re
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Tuple


@dataclass
class CheckResult:
    """Result of a single check."""

    name: str
    passed: bool
    message: str
    file: str = ""
    line: int = 0
    severity: str = "warning"  # info, warning, error


@dataclass
class StripeAudit:
    """Complete Stripe implementation audit results."""

    project_path: Path
    results: List[CheckResult] = field(default_factory=list)
    stripe_lib_found: bool = False
    webhook_verification_found: bool = False
    subscription_handling_found: bool = False
    issues: List[Tuple[str, int, str]] = field(default_factory=list)

    @property
    def passed(self) -> bool:
        """Check if audit passed (no errors)."""
        return not any(r.severity == "error" for r in self.results)

    @property
    def score(self) -> int:
        """Calculate implementation score (0-100)."""
        if not self.results:
            return 0
        passed = sum(1 for r in self.results if r.passed)
        return int((passed / len(self.results)) * 100)


class StripeSubscriptionChecker:
    """Checks for proper Stripe subscription implementation."""

    # Patterns indicating Stripe is used
    STRIPE_INDICATORS = {
        # Python
        "import stripe",
        "from stripe",
        "stripe.api_key",
        "stripe.Webhook.construct_event",
        "stripe.checkout.Session",
        "stripe.Subscription",
        "stripe.Customer",
        # TypeScript/JavaScript
        "from 'stripe'",
        'from "stripe"',
        "require('stripe')",
        'require("stripe")',
        "new Stripe(",
        "stripe.webhooks.constructEvent",
        "stripe.checkout.sessions.create",
        "stripe.subscriptions",
        "stripe.customers",
        # Go
        "stripe-go",
        "stripe.Key",
        "webhook.ConstructEvent",
        "checkout/session",
        # Ruby
        "require 'stripe'",
        "Stripe.api_key",
        "Stripe::Webhook.construct_event",
        "Stripe::Checkout::Session",
        # Rust
        "stripe-rust",
        "stripe::Webhook",
    }

    # ...existing code...
