"""
Create the Excel import template for KPI import
"""
import os
import sys
from openpyxl import Workbook, load_workbook

# Ensure templates directory exists
template_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates')
os.makedirs(template_dir, exist_ok=True)
print(f"Templates directory: {template_dir}")

# Create workbook
wb = Workbook()
ws = wb.active
ws.title = "KPI导入模板"

# Headers
headers = ['kpi_code', 'kpi_name', 'period', 'actual_value', 'unit', 'dimension']
for col_idx, header in enumerate(headers, 1):
    ws.cell(row=1, column=col_idx, value=header)

# Sample data - 商贸零售行业
sample_data = [
    ['F_REVENUE', '营业收入', '2026-06', 500000, '万元', 'finance'],
    ['F_PROFIT_RATE', '销售毛利率', '2026-06', 28.5, '%', 'finance'],
]

for row_idx, row_data in enumerate(sample_data, 2):
    for col_idx, value in enumerate(row_data, 1):
        ws.cell(row=row_idx, column=col_idx, value=value)

# Save
output_path = os.path.join(template_dir, 'kpi_import_template.xlsx')
wb.save(output_path)
print(f"Excel模板已创建: {output_path}")

# Verify
wb2 = load_workbook(output_path)
ws2 = wb2.active
print(f"\n验证文件内容:")
for row in ws2.iter_rows(min_row=1, max_row=3, values_only=True):
    print(f"  {row}")
