# -*- coding: utf-8 -*-
import json
import os
from pathlib import Path

from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = "创建一个新的插件应用结构"

    def add_arguments(self, parser):
        parser.add_argument(
            "plugin_name",
            type=str,
            help="插件应用名称（使用下划线命名，如：user_feedback）",
        )
        parser.add_argument(
            "--author",
            type=str,
            default="系统管理员",
            help='插件作者（默认为"系统管理员"）',
        )
        parser.add_argument(
            "--verbose-name",
            type=str,
            help="插件显示名称（中文名称）",
        )
        parser.add_argument(
            "--structure",
            type=str,
            choices=["folder", "traditional"],
            default="folder",
            help="插件结构模式: folder(文件夹结构) 或 traditional(传统结构)",
        )

    def handle(self, *args, **options):
        plugin_name = options["plugin_name"]
        author = options["author"]
        verbose_name = options["verbose_name"] or plugin_name.replace("_", " ").title()
        structure_mode = options["structure"]

        # 验证插件名称
        if not plugin_name.isidentifier():
            raise CommandError(f'插件名称 "{plugin_name}" 不是有效的Python标识符')

        # 检查插件是否已存在
        plugins_dir = Path("plugins")
        if not plugins_dir.exists():
            plugins_dir.mkdir(parents=True, exist_ok=True)
            self.stdout.write(f"创建plugins目录: {plugins_dir}")

        plugin_path = plugins_dir / plugin_name
        if plugin_path.exists():
            raise CommandError(f"插件目录已存在: {plugin_path}")

        try:
            if structure_mode == "folder":
                self.create_folder_structure(plugin_path, plugin_name, author, verbose_name)
            else:  # traditional
                self.create_traditional_structure(plugin_path, plugin_name, author, verbose_name)

            self.stdout.write(
                self.style.SUCCESS(
                    f'✅ 插件 "{plugin_name}" 创建成功！\n'
                    f"   结构模式: {structure_mode}\n"
                    f"   路径: {plugin_path}\n"
                    f"   下一步:\n"
                    f"   1. 修改插件配置: {plugin_path}/plugin_meta.json\n"
                    f"   2. 实现业务逻辑\n"
                    f"   3. 在管理后台启用插件\n"
                    f"   4. 运行迁移: python manage.py migrate {plugin_name}"
                )
            )
        except Exception as e:
            # 清理已创建的目录
            if plugin_path.exists():
                import shutil

                shutil.rmtree(plugin_path)
            raise CommandError(f"创建插件失败: {e}")

    def create_folder_structure(self, plugin_path, plugin_name, author, verbose_name):
        """创建文件夹结构插件（推荐）"""

        # 创建主目录
        plugin_path.mkdir(parents=True)

        # 创建 __init__.py
        (plugin_path / "__init__.py").write_text("# 插件主文件\n", encoding="utf-8")

        # 创建 dependencies.txt
        dependencies_content = """
#
# INSTALLED_APPS 依赖:
# 如果插件需要其他Django应用，请在此列出（每行一个）:
# 示例:
# django.contrib.comments
# some_other_app
"""
        (plugin_path / "dependencies.txt").write_text(dependencies_content, encoding="utf-8")

        # 创建 admin 文件夹结构
        admin_dir = plugin_path / "admin"
        admin_dir.mkdir()
        (admin_dir / "__init__.py").write_text("# 管理员界面配置模块\n", encoding="utf-8")

        # 创建 models 文件夹结构
        models_dir = plugin_path / "models"
        models_dir.mkdir()
        (models_dir / "__init__.py").write_text("# 数据模型模块\n", encoding="utf-8")

        # 创建 views 文件夹结构
        views_dir = plugin_path / "views"
        views_dir.mkdir()
        (views_dir / "__init__.py").write_text("# 视图模块\n", encoding="utf-8")

        # 创建 forms 文件夹（可选）
        forms_dir = plugin_path / "forms"
        forms_dir.mkdir()
        (forms_dir / "__init__.py").write_text("# 表单模块\n", encoding="utf-8")

        # 创建 serializers 文件夹（可选，用于API）
        serializers_dir = plugin_path / "serializers"
        serializers_dir.mkdir()
        (serializers_dir / "__init__.py").write_text("# 序列化器模块\n", encoding="utf-8")

        # 创建 api 文件夹（可选，用于API视图）
        api_dir = plugin_path / "api"
        api_dir.mkdir()
        (api_dir / "__init__.py").write_text("# API模块\n", encoding="utf-8")

        # 创建管理文件
        (admin_dir / "admin.py").write_text(
            """# 管理员界面配置
from django.contrib import admin
# from ..models import *  # 导入模型

# 在这里注册模型
# admin.site.register(YourModel)
""",
            encoding="utf-8",
        )

        # 创建模型文件
        (models_dir / "models.py").write_text(
            """# 数据模型定义
from django.db import models

# 在这里定义你的模型
# class YourModel(models.Model):
#     name = models.CharField(max_length=100)
#     created_at = models.DateTimeField(auto_now_add=True)
    
#     class Meta:
#         verbose_name = "模型名称"
#         verbose_name_plural = verbose_name
""",
            encoding="utf-8",
        )

        # 创建视图文件
        (views_dir / "views.py").write_text(
            """# 视图逻辑
# from django.views.generic import TemplateView, ListView, DetailView
# from django.shortcuts import render
# from ..models.models import YourModel

# 示例视图
# class IndexView(TemplateView):
#     template_name = 'your_app/index.html'
    
#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context['title'] = '首页'
#         return context
""",
            encoding="utf-8",
        )

        # 创建表单文件
        (forms_dir / "forms.py").write_text(
            """# 表单定义
# from django import forms
# from ..models.models import YourModel

# 示例表单
# class YourForm(forms.ModelForm):
#     class Meta:
#         model = YourModel
#         fields = ['name]
""",
            encoding="utf-8",
        )

        # 创建 apps.py
        apps_content = f"""from django.apps import AppConfig
from apps.core.services.route_service import register_app_urls


class {self.camel_case(plugin_name)}Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'plugins.{plugin_name}'
    verbose_name = "{verbose_name}"

    def ready(self):
        # 自动注册路由
        register_app_urls(
            prefix="{plugin_name}",  # URL前缀
            app_name=self.name,  # 应用命名空间
            priority=True)
        
        # 导入信号处理器（如果有）
        # from . import signals
"""
        (plugin_path / "apps.py").write_text(apps_content, encoding="utf-8")

        # 创建 plugin_meta.json
        self.create_plugin_meta(plugin_path, plugin_name, author, verbose_name)

        # 创建 migrations 目录
        migrations_dir = plugin_path / "migrations"
        migrations_dir.mkdir()
        (migrations_dir / "__init__.py").write_text("# 数据库迁移文件\n", encoding="utf-8")

        # 创建静态文件目录结构
        self.create_static_files(plugin_path, plugin_name)

        # 创建模板目录结构
        self.create_templates(plugin_path, plugin_name, verbose_name)

        # 创建自定义模板标签目录
        self.create_templatetags(plugin_path, plugin_name)

        # 创建测试目录
        self.create_tests(plugin_path, plugin_name)

        # 创建 urls.py
        self.create_urls(plugin_path, plugin_name)

        # 创建 utils.py
        self.create_utils(plugin_path)

        # 创建 signals.py（可选）
        (plugin_path / "signals.py").write_text(
            """# 信号处理器
# from django.db.models.signals import post_save
# from django.dispatch import receiver
# from .models.models import YourModel

# @receiver(post_save, sender=YourModel)
# def handle_model_save(sender, instance, created, **kwargs):
#     if created:
#         print(f"新建对象: {instance}")
#     else:
#         print(f"更新对象: {instance}")
""",
            encoding="utf-8",
        )

        # 创建 README.md
        self.create_readme(plugin_path, plugin_name, verbose_name, structure="folder")

        # 创建 requirements.txt（可选依赖）
        (plugin_path / "requirements.txt").write_text(
            "# 插件依赖包\n# package_name==version\n", encoding="utf-8"
        )

    def create_traditional_structure(self, plugin_path, plugin_name, author, verbose_name):
        """创建传统Django应用结构"""

        # 创建主目录
        plugin_path.mkdir(parents=True)

        # 创建 __init__.py
        (plugin_path / "__init__.py").write_text("# 插件主文件\n", encoding="utf-8")

        # 创建 dependencies.txt
        dependencies_content = """# 插件依赖声明
# 每行一个依赖包，格式: 包名==版本号
# 示例:
# django-crispy-forms==1.14.0
# requests==2.28.1
#
# 这些依赖会在插件安装时自动检查并提示安装
#
# INSTALLED_APPS 依赖:
# 如果插件需要其他Django应用，请在此列出（每行一个）:
# 示例:
# django.contrib.comments
# some_other_app
"""
        (plugin_path / "dependencies.txt").write_text(dependencies_content, encoding="utf-8")

        # 创建 admin.py
        admin_content = """# 管理员界面配置
from django.contrib import admin
from .models import *  # 导入模型

# 在这里注册模型
# admin.site.register(YourModel)
"""
        (plugin_path / "admin.py").write_text(admin_content, encoding="utf-8")

        # 创建 apps.py
        apps_content = f"""from django.apps import AppConfig
from apps.core.services.route_service import register_app_urls


class {self.camel_case(plugin_name)}Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'plugins.{plugin_name}'
    verbose_name = "{verbose_name}"

    def ready(self):
        # 自动注册路由
        register_app_urls(
            prefix="{plugin_name}",  # URL前缀
            app_name=self.name,  # 应用命名空间
            priority=True)
"""
        (plugin_path / "apps.py").write_text(apps_content, encoding="utf-8")

        # 创建 plugin_meta.json
        self.create_plugin_meta(plugin_path, plugin_name, author, verbose_name)

        # 创建 migrations 目录
        migrations_dir = plugin_path / "migrations"
        migrations_dir.mkdir()
        (migrations_dir / "__init__.py").write_text("# 数据库迁移文件\n", encoding="utf-8")

        # 创建 models.py
        models_content = """# 数据模型定义
from django.db import models

# 在这里定义你的模型
# class YourModel(models.Model):
#     name = models.CharField(max_length=100)
#     created_at = models.DateTimeField(auto_now_add=True)
    
#     class Meta:
#         verbose_name = "模型名称"
#         verbose_name_plural = verbose_name
"""
        (plugin_path / "models.py").write_text(models_content, encoding="utf-8")

        # 创建静态文件目录结构
        self.create_static_files(plugin_path, plugin_name)

        # 创建模板目录结构
        self.create_templates(plugin_path, plugin_name, verbose_name)

        # 创建自定义模板标签目录
        self.create_templatetags(plugin_path, plugin_name)

        # 创建测试目录
        self.create_tests(plugin_path, plugin_name)

        # 创建 urls.py
        self.create_urls(plugin_path, plugin_name)

        # 创建 utils.py
        self.create_utils(plugin_path)

        # 创建 views.py
        views_content = f"""# 视图逻辑
# from django.views.generic import TemplateView, ListView, DetailView
# from django.shortcuts import render
# from .models import YourModel

# 示例视图
# class IndexView(TemplateView):
#     template_name = '{plugin_name}/index.html'
    
#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context['title'] = '{verbose_name}'
#         return context
"""
        (plugin_path / "views.py").write_text(views_content, encoding="utf-8")

        # 创建 forms.py
        forms_content = """# 表单定义
# from django import forms
# from .models import YourModel

# 示例表单
# class YourForm(forms.ModelForm):
#     class Meta:
#         model = YourModel
#         fields = ['name']
"""
        (plugin_path / "forms.py").write_text(forms_content, encoding="utf-8")

        # 创建 README.md
        self.create_readme(plugin_path, plugin_name, verbose_name, structure="traditional")

        # 创建 requirements.txt（可选依赖）
        (plugin_path / "requirements.txt").write_text(
            "# 插件依赖包\n# package_name==version\n", encoding="utf-8"
        )

        # 创建 signals.py
        signals_content = """# 信号处理器
# from django.db.models.signals import post_save
# from django.dispatch import receiver
# from .models import YourModel

# @receiver(post_save, sender=YourModel)
# def handle_model_save(sender, instance, created, **kwargs):
#     if created:
#         print(f"新建对象: {instance}")
#     else:
#         print(f"更新对象: {instance}")
"""
        (plugin_path / "signals.py").write_text(signals_content, encoding="utf-8")

    def create_plugin_meta(self, plugin_path, plugin_name, author, verbose_name):
        """创建plugin_meta.json文件"""
        meta_data = {
            "name": verbose_name,
            "author": author,
            "version": "1.0.0",
            "djacore_version": "4.2+",
            "description": f"<p>{verbose_name}插件</p><ul><li>功能点1</li><li>功能点2</li><li>功能点3</li></ul>",
            "is_active": False,
            "dependency_status": "pending",
            "last_dependency_check": "2026-01-01T00:00:00.000000",
            "requires_db": True,
            "migration_status": "pending",
        }
        (plugin_path / "plugin_meta.json").write_text(
            json.dumps(meta_data, ensure_ascii=False, indent=2), encoding="utf-8"
        )

    def create_static_files(self, plugin_path, plugin_name):
        """创建静态文件目录结构"""
        static_dir = plugin_path / "static"
        css_dir = static_dir / "css"
        js_dir = static_dir / "js"
        images_dir = static_dir / "images"

        css_dir.mkdir(parents=True)
        js_dir.mkdir(parents=True)
        images_dir.mkdir(parents=True)

        # 创建示例CSS文件
        css_content = f"""/* {plugin_name} 插件自定义样式 */
.plugin-container {{
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 5px;
}}

.plugin-title {{
    color: #333;
    border-bottom: 2px solid #007bff;
    padding-bottom: 10px;
}}
"""
        (css_dir / f"{plugin_name}.css").write_text(css_content, encoding="utf-8")

        # 创建示例JS文件
        js_query_content = """// 前端交互逻辑
console.log('插件JavaScript文件已加载');

function queryData() {
    // 数据查询逻辑
    console.log('查询数据...');
    return fetch('/api/data/')
        .then(response => response.json())
        .then(data => {
            console.log('数据:', data);
            return data;
        });
}

// 初始化函数
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM已加载，插件已初始化');
});
"""
        (js_dir / "query.js").write_text(js_query_content, encoding="utf-8")

        js_map_content = """// 地图展示逻辑（如果不需要可以删除）
console.log('地图组件已加载');

// 示例地图函数
function initMap(elementId, coordinates) {
    console.log('初始化地图:', elementId, coordinates);
    // 这里可以集成地图库，如Leaflet、OpenLayers等
}
"""
        (js_dir / "map.js").write_text(js_map_content, encoding="utf-8")

    def create_templates(self, plugin_path, plugin_name, verbose_name):
        """创建模板目录结构"""
        templates_dir = plugin_path / "templates" / plugin_name
        templates_dir.mkdir(parents=True)

        # 创建详情页面模板
        detail_content = f"""{{% extends "admin/base.html" %}}
{{% load static %}}

{{% block content %}}
<div class="plugin-container">
    <h2 class="plugin-title">{verbose_name} - 详情页面</h2>
    <p>这是插件的详情页面模板。</p>
    
    <div class="alert alert-info">
        <strong>提示：</strong> 这是一个示例插件页面。
    </div>
    
    <div class="plugin-content">
        <p>您可以在这里添加插件的内容和功能。</p>
        
        <div class="card mt-4">
            <div class="card-header">
                插件信息
            </div>
            <div class="card-body">
                <h5 class="card-title">{plugin_name}</h5>
                <p class="card-text">版本: 1.0.0</p>
                <a href="#" class="btn btn-primary">了解更多</a>
            </div>
        </div>
    </div>
    
    <link rel="stylesheet" href="{{% static '{plugin_name}/css/{plugin_name}.css' %}}">
    <script src="{{% static '{plugin_name}/js/query.js' %}}"></script>
</div>
{{% endblock %}}
"""
        (templates_dir / "detail.html").write_text(detail_content, encoding="utf-8")

        # 创建列表页面模板
        list_content = f"""{{% extends "admin/base.html" %}}
{{% load static %}}

{{% block content %}}
<div class="plugin-container">
    <h2 class="plugin-title">{verbose_name} - 列表页面</h2>
    
    <div class="card">
        <div class="card-header">
            数据列表
        </div>
        <div class="card-body">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {{% for item in items %}}
                    <tr>
                        <td>{{{{ item.id }}}}</td>
                        <td>{{{{ item.name }}}}</td>
                        <td>{{{{ item.created_at }}}}</td>
                        <td>
                            <a href="#" class="btn btn-sm btn-primary">查看</a>
                            <a href="#" class="btn btn-sm btn-warning">编辑</a>
                        </td>
                    </tr>
                    {{% empty %}}
                    <tr>
                        <td colspan="4" class="text-center">暂无数据</td>
                    </tr>
                    {{% endfor %}}
                </tbody>
            </table>
        </div>
    </div>
    
    <link rel="stylesheet" href="{{% static '{plugin_name}/css/{plugin_name}.css' %}}">
    <script src="{{% static '{plugin_name}/js/query.js' %}}"></script>
</div>
{{% endblock %}}
"""
        (templates_dir / "list.html").write_text(list_content, encoding="utf-8")

    def create_templatetags(self, plugin_path, plugin_name):
        """创建自定义模板标签目录"""
        templatetags_dir = plugin_path / "templatetags"
        templatetags_dir.mkdir()
        (templatetags_dir / "__init__.py").write_text("# 自定义模板标签\n", encoding="utf-8")

        tags_content = f'''# 自定义模板标签
from django import template

register = template.Library()

@register.filter
def add_prefix(value, prefix):
    """添加前缀过滤器示例"""
    return f"{{prefix}}_{{value}}"

@register.filter
def custom_filter(value):
    """自定义过滤器示例"""
    return f"{{value}}_processed"

@register.simple_tag
def get_plugin_info():
    """获取插件信息标签"""
    return "{plugin_name} plugin v1.0.0"

@register.inclusion_tag('{plugin_name}/info_card.html')
def plugin_info_card(title="插件信息"):
    """包含标签示例"""
    return {{
        'title': title,
        'version': '1.0.0',
        'author': '系统管理员',
    }}
'''
        (templatetags_dir / f"{plugin_name}_tags.py").write_text(tags_content, encoding="utf-8")

    def create_tests(self, plugin_path, plugin_name):
        """创建测试目录"""
        tests_dir = plugin_path / "tests"
        tests_dir.mkdir()
        (tests_dir / "__init__.py").write_text("# 测试文件\n", encoding="utf-8")

        # 创建模型测试
        test_models_content = '''# 模型测试用例
from django.test import TestCase
# from .models.models import YourModel

# class YourModelTests(TestCase):
#     def test_model_creation(self):
#         """测试模型创建"""
#         obj = YourModel.objects.create(name="Test")
#         self.assertEqual(str(obj), "Test")
    
#     def test_model_fields(self):
#         """测试模型字段"""
#         obj = YourModel(name="Test Name")
#         self.assertEqual(obj.name, "Test Name")
'''
        (tests_dir / "test_models.py").write_text(test_models_content, encoding="utf-8")

        # 创建视图测试
        test_views_content = f'''# 视图测试用例
from django.test import TestCase
from django.urls import reverse

# class YourViewTests(TestCase):
#     def test_view_status_code(self):
#         """测试视图状态码"""
#         response = self.client.get(reverse('{plugin_name}:list'))
#         self.assertEqual(response.status_code, 200)
    
#     def test_view_template(self):
#         """测试视图模板"""
#         response = self.client.get(reverse('{plugin_name}:list'))
#         self.assertTemplateUsed(response, '{plugin_name}/list.html')
'''
        (tests_dir / "test_views.py").write_text(test_views_content, encoding="utf-8")

        # 创建API测试
        test_api_content = '''# API测试用例
from django.test import TestCase
from rest_framework.test import APITestCase
from rest_framework import status

# class YourAPITests(APITestCase):
#     def test_api_endpoint(self):
#         """测试API端点"""
#         response = self.client.get('/api/your-endpoint/')
#         self.assertEqual(response.status_code, status.HTTP_200_OK)
'''
        (tests_dir / "test_api.py").write_text(test_api_content, encoding="utf-8")

    def create_urls(self, plugin_path, plugin_name):
        """创建URL配置"""
        urls_content = f"""from django.urls import path
from . import views

app_name = '{plugin_name}'

urlpatterns = [
    # 示例路由
    # path('', views.IndexView.as_view(), name='index'),
    # path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    
    # API路由示例
    # path('api/list/', views.YourListView.as_view(), name='api_list'),
    # path('api/create/', views.YourCreateView.as_view(), name='api_create'),
]
"""
        (plugin_path / "urls.py").write_text(urls_content, encoding="utf-8")

    def create_utils(self, plugin_path):
        """创建工具类"""
        utils_content = '''# 工具类
import logging
from datetime import datetime
import hashlib

logger = logging.getLogger(__name__)

def example_util():
    """工具函数示例"""
    return "utility function"

def generate_unique_id(data):
    """生成唯一ID"""
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f")
    data_str = str(data) + timestamp
    return hashlib.md5(data_str.encode()).hexdigest()[:8]

def validate_input(data, required_fields):
    """验证输入数据"""
    errors = []
    for field in required_fields:
        if field not in data or not data[field]:
            errors.append(f"字段 '{field}' 是必填项")
    return errors

class PluginHelper:
    """插件助手类"""
    
    @staticmethod
    def get_config():
        """获取插件配置"""
        return {
            'name': '插件助手',
            'version': '1.0.0',
        }
    
    @staticmethod
    def format_data(data):
        """格式化数据"""
        if isinstance(data, dict):
            return {k: str(v) for k, v in data.items()}
        return str(data)
'''
        (plugin_path / "utils.py").write_text(utils_content, encoding="utf-8")

    def create_readme(self, plugin_path, plugin_name, verbose_name, structure="folder"):
        """创建README文件"""
        if structure == "folder":
            dir_structure = f"""{plugin_name}/
├── __init__.py
├── admin/
│   ├── __init__.py
│   └── admin.py
├── apps.py
├── dependencies.txt
├── forms/
│   ├── __init__.py
│   └── forms.py
├── migrations/
│   └── __init__.py
├── models/
│   ├── __init__.py
│   └── models.py
├── plugin_meta.json
├── requirements.txt
├── serializers/
│   └── __init__.py
├── signals.py
├── static/
│   ├── css/
│   │   └── {plugin_name}.css
│   ├── js/
│   │   ├── query.js
│   │   └── map.js
│   └── images/
├── templates/
│   └── {plugin_name}/
│       ├── detail.html
│       └── list.html
├── templatetags/
│   ├── __init__.py
│   └── {plugin_name}_tags.py
├── tests/
│   ├── __init__.py
│   ├── test_models.py
│   └── test_views.py
├── urls.py
├── utils.py
└── views/
    ├── __init__.py
    └── views.py"""
        else:  # traditional
            dir_structure = f"""{plugin_name}/
├── __init__.py
├── admin.py
├── apps.py
├── dependencies.txt
├── forms.py
├── migrations/
│   └── __init__.py
├── models.py
├── plugin_meta.json
├── requirements.txt
├── signals.py
├── static/
│   ├── css/
│   │   └── {plugin_name}.css
│   ├── js/
│   │   ├── query.js
│   │   └── map.js
│   └── images/
├── templates/
│   └── {plugin_name}/
│       ├── detail.html
│       └── list.html
├── templatetags/
│   ├── __init__.py
│   └── {plugin_name}_tags.py
├── tests/
│   ├── __init__.py
│   ├── test_models.py
│   └── test_views.py
├── urls.py
├── utils.py
└── views.py"""

        readme_content = f"""# {verbose_name} 插件

## 插件说明
这是一个 {verbose_name} 插件，使用{"文件夹" if structure == "folder" else "传统"}结构。

## 结构模式: {structure.upper()}
{"文件夹结构 (推荐): 将不同功能模块分离到不同的文件夹中，便于维护和扩展。" if structure == "folder" else "传统结构: 使用标准的Django应用结构，所有功能模块在根目录下。"}

## 目录结构
{dir_structure}
## 依赖管理
插件依赖声明在 `dependencies.txt` 文件中。格式如下：

1. **Python包依赖** (每行一个):
package_name==version
2. **Django应用依赖** (每行一个):
django_app_name
## 安装说明
1. 在管理后台启用插件
2. 运行数据库迁移：`python manage.py migrate {plugin_name}`
3. 安装依赖包：`pip install -r plugins/{plugin_name}/requirements.txt`

## 使用说明
1. 修改 `plugin_meta.json` 更新插件信息
2. 修改 `models/` 或 `models.py` 定义数据模型
3. 修改 `views/` 或 `views.py` 编写视图逻辑
4. 修改 `urls.py` 配置路由
5. 修改模板文件定制界面
6. 修改 `admin/` 或 `admin.py` 配置后台管理

## 开发说明
1. 在 `dependencies.txt` 中添加必要的依赖
2. 在 `tests/` 目录下编写测试用例
3. 使用 `templatetags/` 创建自定义模板标签
4. 在 `utils.py` 中添加通用工具函数
5. 在 `signals.py` 中定义信号处理器

## API开发
1. 在 `serializers/` 目录下创建序列化器
2. 在 `api/` 目录下创建API视图
3. 在 `urls.py` 中配置API路由

## 注意事项
1. 确保插件名称符合Python标识符规范
2. 数据库迁移前请先启用插件
3. 修改 `dependencies.txt` 后需要重启应用
4. 静态文件路径: `static/{plugin_name}/`
5. 模板文件路径: `templates/{plugin_name}/`
"""
        # 这里就是您提到的代码行
        (plugin_path / "README.md").write_text(readme_content, encoding="utf-8")

    def camel_case(self, snake_str):
        """将下划线命名转换为驼峰命名（用于类名）"""
        components = snake_str.split("_")
        return "".join(x.title() for x in components)
