"""Run all CMA tasks by direct import - no subprocess needed"""
import sys, os

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

# Load env
from dotenv import load_dotenv
load_dotenv()

# Import all needed modules
from app.database import get_session_local
from app.models import DataSourceConfig, KPIValue, KPIDefinition
from openpyxl import Workbook, load_workbook
import urllib.request, json

print("=" * 70)
print("【子任务1】插入数据源记录")
print("=" * 70)

db = get_session_local()()
try:
    existing = db.query(DataSourceConfig).filter(DataSourceConfig.name == 'ERP系统 - 博海网络').first()
    if existing:
        print(f"  [OK] 已存在: id={existing.id}")
    else:
        s = 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(s); db.commit(); db.refresh(s)
        print(f"  [OK] 插入成功: id={s.id}")
    for r in db.query(DataSourceConfig).all():
        print(f"    id={r.id}, name={r.name}, type={r.source_type}, status={r.status}")
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)
wb = Workbook()
ws = wb.active
ws.title = 'KPI导入模板'
for i, h in enumerate(['kpi_code', 'kpi_name', 'period', 'actual_value', 'unit', 'dimension'], 1):
    ws.cell(row=1, column=i, value=h)
sample = [
    ['F_REVENUE', '营业收入', '2026-06', 500000, '万元', 'finance'],
    ['F_PROFIT_RATE', '销售毛利率', '2026-06', 28.5, '%', 'finance'],
]
for ri, rd in enumerate(sample, 2):
    for ci, v in enumerate(rd, 1):
        ws.cell(row=ri, column=ci, value=v)
fp = os.path.join(template_dir, 'kpi_import_template.xlsx')
wb.save(fp)
print(f"  [OK] 模板已创建: {fp} ({os.path.getsize(fp)} bytes)")

print()
print("=" * 70)
print("【子任务2】ERP同步验证")
print("=" * 70)

# Check backend
try:
    req = urllib.request.Request('http://127.0.0.1:8010/health')
    resp = urllib.request.urlopen(req, timeout=3)
    print(f"  [OK] 后端服务运行中: {json.loads(resp.read())}")
except Exception as e:
    print(f"  [INFO] 后端服务未运行: {e}")

# Run ERP sync - dry run then actual
from scripts.erp_sync import run_sync
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')

print("\n  --- dry-run ---")
run_sync(dry_run=True)

print("\n  --- 实际同步 ---")
run_sync(dry_run=False)

print("\n  --- 验证 kpi_values ---")
db = get_session_local()()
try:
    vals = db.query(KPIValue).filter(KPIValue.source_type == 'erp').all()
    print(f"  source_type='erp' 记录数: {len(vals)}")
    for v in vals:
        k = db.query(KPIDefinition).filter(KPIDefinition.id == v.kpi_id).first()
        kc = k.kpi_code if k else '?'
        print(f"    {kc} | {v.period} | {v.actual_value} | {v.data_status} | {v.remark[:40] if v.remark else ''}")
finally:
    db.close()

print()
print("=" * 70)
print("【子任务3】Crontab设定")
print("=" * 70)

# Read current crontab and check
import subprocess
result = subprocess.run(['crontab', '-l'], capture_output=True, text=True, timeout=10)
existing = result.stdout if result.returncode == 0 else ''
cron_line = "0 1 * * * cd /root/cma-management/backend && /usr/bin/python3 scripts/erp_sync.py >> /var/log/cma-erp-sync.log 2>&1"

if 'erp_sync' in existing:
    print("  [OK] cron任务已存在")
else:
    new_cron = existing.strip() + '\n' + cron_line + '\n' if existing.strip() else cron_line + '\n'
    r = subprocess.run(['crontab'], input=new_cron, capture_output=True, text=True, timeout=10)
    if r.returncode == 0:
        print(f"  [OK] cron已添加: {cron_line}")
    else:
        print(f"  [WARN] 添加失败: {r.stderr}")
        print(f"  请手动运行: (crontab -l 2>/dev/null; echo '{cron_line}') | crontab -")

print()
print("=" * 50)
print("所有任务执行完毕")
print("=" * 50)
