from nikame.codegen.base import BaseCodegen, CodegenContext, WiringInfo
from nikame.config.schema import NikameConfig
from nikame.codegen.ai_synthesizer import AISynthesizer
from nikame.utils.logger import console


class StripeCodegen(BaseCodegen):
    NAME = "stripe"
    DESCRIPTION = "Stripe subscription billing and webhook integration"
    TRIGGER_MODULES = ["fastapi", "postgres"]

    def __init__(self, ctx: CodegenContext, config: NikameConfig) -> None:
        super().__init__(ctx, config)
        self.config = config
        self.ai = AISynthesizer()

    def generate(self) -> list[tuple[str, str]]:
        console.print("[info]Synthesizing dynamic Stripe webhook and checkout API...[/info]")
        
        prompt = (
            "You are an expert backend engineer implementing Stripe for an application. "
            "Write a fully functional FastAPI router that handles:\n"
            "1. A Checkout Session creation endpoint.\n"
            "2. A Stripe Webhook receiver that firmly handles `checkout.session.completed`.\n"
            "Assume the Stripe keys are in `settings.STRIPE_API_KEY` and `settings.STRIPE_WEBHOOK_SECRET`.\n"
            "Output ONLY the raw Python code."
        )
        
        context = self.config.description or "A SaaS app with subscription billing."
        router_code = self.ai.synthesize_code(prompt, context)
        
        return [
            ("app/api/v1/endpoints/billing.py", router_code),
        ]

    def wiring(self) -> WiringInfo:
        return WiringInfo(
            imports=["from billing import router as billing_router"],
            routers=["app.include_router(billing_router)"],
            requirements=["stripe>=8.0.0"],
            settings_fields=[
                "STRIPE_API_KEY: str = ''",
                "STRIPE_WEBHOOK_SECRET: str = ''",
            ]
        )
