"""
Streamlit Client Copier.

Copies generated Python API clients to Streamlit admin app.
"""

from __future__ import annotations

import shutil
from pathlib import Path
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from ..models import StreamlitAdminConfig


class StreamlitClientCopier:
    """
    Copies Python API clients to django_cfg.modules.streamlit_admin.api.generated.

    Copies the combined "cfg" group which contains all django_cfg endpoints
    (accounts, dashboard, grpc, rq, centrifugo, totp, etc.)

    Target is always: django_cfg/modules/streamlit_admin/api/generated/
    """

    __slots__ = ("_source_path", "_target_path")

    def __init__(
        self,
        source_path: Optional[Path] = None,
        target_path: Optional[Path] = None,
        base_dir: Optional[Path] = None,
    ):
        if base_dir is None:
            from django.conf import settings
            base_dir = Path(settings.BASE_DIR)

        self._source_path = source_path or (
            base_dir / "openapi" / "clients" / "python"
        )

        if target_path:
            self._target_path = target_path
        else:
            # Always copy to django_cfg module
            self._target_path = self._get_module_path() / "api" / "generated"

    @staticmethod
    def _get_module_path() -> Path:
        """Get path to streamlit_admin module in django_cfg."""
        import django_cfg.modules.streamlit_admin as module
        return Path(module.__file__).parent

    @classmethod
    def from_django_config(cls) -> "StreamlitClientCopier":
        """Create copier from Django configuration."""
        from django_cfg.core.config import get_current_config

        config = get_current_config()
        if not config.streamlit_admin:
            raise ValueError("streamlit_admin not configured")

        return cls()

    @property
    def source_path(self) -> Path:
        """Get source path for Python clients."""
        return self._source_path

    @property
    def target_path(self) -> Path:
        """Get target path for Streamlit clients."""
        return self._target_path

    def copy(self) -> dict:
        """
        Copy clients to Streamlit app.

        Returns:
            dict with copy statistics:
            - copied_packages: list of copied package names
            - created_files: list of generated files
            - target_path: where files were copied
        """
        if not self._source_path.exists():
            raise FileNotFoundError(
                f"Python clients not found at {self._source_path}. "
                "Run: python manage.py generate_client --python"
            )

        # Clean and create target directory
        if self._target_path.exists():
            shutil.rmtree(self._target_path)
        self._target_path.mkdir(parents=True, exist_ok=True)

        stats = {
            "copied_packages": [],
            "created_files": [],
            "target_path": str(self._target_path),
        }

        # Copy "cfg" package (combined client with all django_cfg endpoints)
        cfg_dir = self._source_path / "cfg"
        if cfg_dir.is_dir():
            target_pkg = self._target_path / "cfg"
            shutil.copytree(cfg_dir, target_pkg)
            stats["copied_packages"].append("cfg")

        # Generate __init__.py
        self._generate_init()
        stats["created_files"].append("__init__.py")

        return stats

    def _generate_init(self) -> None:
        """Generate __init__.py with re-exports from cfg."""
        content = '''"""
Generated API Client.

Auto-generated by django-cfg. Do not edit manually.

Usage:
    from django_cfg.modules.streamlit_admin.api.generated import SyncAPIClient

    api = SyncAPIClient("http://localhost:8000")
    api.set_token("your-jwt-token")

    with api:
        profile = api.cfg_user_profile.profile_retrieve()
        charts = api.cfg_dashboard_charts.dashboard_api_charts_activity_retrieve()

Note: Prefer using AdminAPI from parent module for auto-authentication:

    from django_cfg.modules.streamlit_admin.api import AdminAPI

    api = AdminAPI()  # auto base_url + auto token from session
"""

from .cfg import SyncAPIClient
from .cfg.client import APIClient

__all__ = [
    "SyncAPIClient",
    "APIClient",
]
'''
        (self._target_path / "__init__.py").write_text(content)
