"""Frontend organization management generator for Prism.

Generates React organization pages, components, and API client
for multi-tenant organization management with RBAC.
"""

from __future__ import annotations

from pathlib import Path

from prisme.generators.base import GeneratedFile, GeneratorBase
from prisme.spec.stack import FileStrategy
from prisme.utils.template_engine import TemplateRenderer


class FrontendOrgGenerator(GeneratorBase):
    """Generates React organization management components for frontend.

    Produces:
    - Organization API client (TypeScript)
    - Organization list page
    - Organization create page
    - Organization settings page
    - Member management page
    - Organization switcher component
    - Invitation acceptance page
    """

    REQUIRED_TEMPLATES = [
        "frontend/organization/orgApi.ts.jinja2",
        "frontend/organization/OrgList.tsx.jinja2",
        "frontend/organization/OrgCreate.tsx.jinja2",
        "frontend/organization/OrgSettings.tsx.jinja2",
        "frontend/organization/OrgMembers.tsx.jinja2",
        "frontend/organization/OrgSwitcher.tsx.jinja2",
        "frontend/organization/OrgInviteAccept.tsx.jinja2",
        "frontend/organization/OrgLayout.tsx.jinja2",
    ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if not self.auth_config.enabled or not self.auth_config.organization.enabled:
            self.skip_generation = True
            return

        self.renderer = TemplateRenderer()
        self.renderer.validate_templates_exist(self.REQUIRED_TEMPLATES)

        frontend_base = Path(self.generator_config.frontend_output)
        self.pages_path = frontend_base / "pages"
        self.components_path = frontend_base / "components"
        self.lib_path = frontend_base / "lib"

    def _get_common_context(self) -> dict:
        """Build template context for organization templates."""
        config = self.auth_config
        org_config = config.organization

        return {
            "username_field": config.username_field,
            "slug_field": org_config.slug_field,
            "org_roles": [
                {
                    "name": role.name,
                    "permissions": role.permissions,
                    "description": role.description or "",
                }
                for role in org_config.roles
            ],
            "default_org_role": org_config.default_role,
            "allow_multiple_orgs": org_config.allow_multiple_orgs,
            "max_members_per_org": org_config.max_members_per_org,
        }

    def generate_files(self) -> list[GeneratedFile]:
        """Generate all frontend organization files."""
        if getattr(self, "skip_generation", False):
            return []

        ctx = self._get_common_context()
        return [
            self._generate_file(
                "frontend/organization/orgApi.ts.jinja2",
                self.lib_path / "orgApi.ts",
                FileStrategy.ALWAYS_OVERWRITE,
                "Organization API client",
                ctx,
            ),
            self._generate_file(
                "frontend/organization/OrgList.tsx.jinja2",
                self.pages_path / "organizations" / "OrgList.tsx",
                FileStrategy.GENERATE_ONCE,
                "Organization list page",
                ctx,
            ),
            self._generate_file(
                "frontend/organization/OrgCreate.tsx.jinja2",
                self.pages_path / "organizations" / "OrgCreate.tsx",
                FileStrategy.GENERATE_ONCE,
                "Organization create page",
                ctx,
            ),
            self._generate_file(
                "frontend/organization/OrgSettings.tsx.jinja2",
                self.pages_path / "organizations" / "OrgSettings.tsx",
                FileStrategy.GENERATE_ONCE,
                "Organization settings page",
                ctx,
            ),
            self._generate_file(
                "frontend/organization/OrgMembers.tsx.jinja2",
                self.pages_path / "organizations" / "OrgMembers.tsx",
                FileStrategy.GENERATE_ONCE,
                "Organization members page",
                ctx,
            ),
            self._generate_file(
                "frontend/organization/OrgSwitcher.tsx.jinja2",
                self.components_path / "organizations" / "OrgSwitcher.tsx",
                FileStrategy.GENERATE_ONCE,
                "Organization switcher component",
                ctx,
            ),
            self._generate_file(
                "frontend/organization/OrgInviteAccept.tsx.jinja2",
                self.pages_path / "organizations" / "OrgInviteAccept.tsx",
                FileStrategy.GENERATE_ONCE,
                "Invitation acceptance page",
                ctx,
            ),
            self._generate_file(
                "frontend/organization/OrgLayout.tsx.jinja2",
                self.components_path / "organizations" / "OrgLayout.tsx",
                FileStrategy.GENERATE_ONCE,
                "Organization layout component",
                ctx,
            ),
        ]

    def _generate_file(
        self,
        template: str,
        path: Path,
        strategy: FileStrategy,
        description: str,
        context: dict,
    ) -> GeneratedFile:
        content = self.renderer.render_file(template, context=context)
        return GeneratedFile(
            path=path,
            content=content,
            strategy=strategy,
            description=description,
        )
