# -*- coding: utf-8 -*-
"""
导出网站数据
生成CSV文件，方便批量导入
"""
import csv
import sys
from app import create_app
from models import Site, Tag

def export_sites_to_csv():
    """导出网站数据到CSV"""
    app = create_app('development')

    with app.app_context():
        sites = Site.query.order_by(Site.sort_order.desc()).all()

        if not sites:
            print("没有找到任何网站数据")
            return

        # 导出为CSV
        filename = 'sites_export.csv'
        with open(filename, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)

            # 写入表头
            writer.writerow([
                '网站名称',
                'URL',
                '简短描述',
                '详细描述',
                '特色功能',
                '标签(逗号分隔)',
                '排序值',
                '是否可见'
            ])

            # 写入数据
            for site in sites:
                tags_str = ', '.join([tag.name for tag in site.tags])
                writer.writerow([
                    site.name,
                    site.url,
                    site.short_desc or '',
                    site.description or '',
                    site.features or '',
                    tags_str,
                    site.sort_order,
                    '是' if site.is_visible else '否'
                ])

        print(f"✓ 成功导出 {len(sites)} 个网站")
        print(f"  文件: {filename}")
        print("\n网站列表：")
        print("-" * 80)

        for i, site in enumerate(sites, 1):
            tags = ', '.join([tag.name for tag in site.tags])
            print(f"{i}. {site.name}")
            print(f"   URL: {site.url}")
            print(f"   描述: {site.short_desc}")
            print(f"   标签: {tags}")
            print()

if __name__ == '__main__':
    export_sites_to_csv()
