"""
Comprehensive execution script for all 4 CMA sub-tasks
"""
import os
import sys

backend_dir = '/root/cma-management/backend'
os.chdir(backend_dir)
sys.path.insert(0, backend_dir)

from dotenv import load_dotenv
load_dotenv()

from app.database import get_session_local
from app.models import DataSourceConfig
from openpyxl import Workbook, load_workbook

print("=" * 70)
print("子任务1: 配置数据源 - 插入ERP数据源记录")
print("=" * 70)

db = get_session_local()()
try:
    existing = db.query(DataSourceConfig).filter(
        DataSourceConfig.name == 'ERP系统 - 博海网络'
    ).first()
    if existing:
        print(f"[OK] 数据源已存在: id={existing.id}, name={existing.name}")
    else:
        source = DataSourceConfig(
            name='ERP系统 - 博海网络',
            source_type='erp',
            api_endpoint='http://127.0.0.1:8300/api/v1',
            api_key='erp-gateway-key-bhwl-2026',
            sync_type='batch',
            status='active',
        )
        db.add(source)
        db.commit()
        db.refresh(source)
        print(f"[OK] 数据源插入成功: id={source.id}, name={source.name}")

    all_sources = db.query(DataSourceConfig).all()
    print(f"    当前 data_source_config 表记录数: {len(all_sources)}")
    for s in all_sources:
        print(f"    - id={s.id}, name={s.name}, type={s.source_type}, status={s.status}")
except Exception as e:
    print(f"[FAIL] 数据源插入失败: {e}")
    db.rollback()
finally:
    db.close()

print()
print("=" * 70)
print("子任务4: 创建Excel导入模板")
print("=" * 70)

template_dir = os.path.join(backend_dir, 'templates')
os.makedirs(template_dir, exist_ok=True)
print(f"[OK] 确保templates目录存在: {template_dir}")

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

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 = [
    ['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)

output_path = os.path.join(template_dir, 'kpi_import_template.xlsx')
wb.save(output_path)

# Verify
wb2 = load_workbook(output_path)
ws2 = wb2.active
print(f"[OK] Excel模板已创建: {output_path}")
print("    验证文件内容:")
for row in ws2.iter_rows(min_row=1, max_row=3, values_only=True):
    print(f"      {list(row)}")

print()
print("=" * 70)
print("子任务2: 验证ERP同步全链路")
print("=" * 70)

# Check if backend is already running
import urllib.request
import json

try:
    req = urllib.request.Request('http://127.0.0.1:8010/health')
    with urllib.request.urlopen(req, timeout=5) as resp:
        health = json.loads(resp.read().decode())
        print(f"[OK] 后端服务已在8010端口运行: {health}")
except Exception as e:
    print(f"[INFO] 后端服务未运行: {e}")
    print("[INFO] 将在后续步骤中启动后端服务")

# Run erp_sync.py --dry-run
print()
print("--- 运行 erp_sync.py --dry-run ---")
from scripts.erp_sync import run_sync
import logging

# Configure logging to stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')

try:
    run_sync(dry_run=True)
    print("[OK] erp_sync.py --dry-run 执行成功")
except Exception as e:
    print(f"[INFO] dry-run执行结果: {e}")

# Run erp_sync.py actual sync
print()
print("--- 运行 erp_sync.py (实际同步) ---")
try:
    run_sync(dry_run=False)
    print("[OK] erp_sync.py 实际同步执行成功")
except Exception as e:
    print(f"[INFO] 实际同步执行结果: {e}")

# Verify kpi_values table
print()
print("--- 验证 kpi_values 表 ---")
db = get_session_local()()
try:
    from app.models import KPIValue
    erp_values = db.query(KPIValue).filter(KPIValue.source_type == 'erp').all()
    print(f"    source_type='erp' 的记录数: {len(erp_values)}")
    for v in erp_values:
        from app.models import KPIDefinition
        kpi = db.query(KPIDefinition).filter(KPIDefinition.id == v.kpi_id).first()
        kpi_code = kpi.kpi_code if kpi else '?'
        print(f"    - kpi_code={kpi_code}, period={v.period}, value={v.actual_value}, status={v.data_status}")
except Exception as e:
    print(f"[FAIL] 验证失败: {e}")
finally:
    db.close()

print()
print("=" * 70)
print("子任务3: 设定定时同步 (cron)")
print("=" * 70)

cron_line = "0 1 * * * cd /root/cma-management/backend && /usr/bin/python3 scripts/erp_sync.py >> /var/log/cma-erp-sync.log 2>&1"
print(f"[INFO] 需要写入的cron任务: {cron_line}")
print("[INFO] 请使用 'crontab -e' 或运行以下命令添加:")
print(f"  (crontab -l 2>/dev/null; echo '{cron_line}') | crontab -")
print()

print("=" * 70)
print("所有子任务执行完成")
print("=" * 70)
