"""对外法定报表适配 — 数据库迁移
补充资产负债表科目（资产/负债/所有者权益），按新30号准则经营/投资/筹资分类打标
"""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.database import get_engine
from sqlalchemy import text
import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("migrate_statutory")

# (科目编码, 科目名称, 上级, 级别, 类别, 新30号准则分类)
# 新30号准则分类: operating经营类 / investing投资类 / financing筹资类 / equity权益
BALANCE_SHEET_SUBJECTS = [
    # ── 资产类 (category=asset) ──
    ('1001', '库存现金', None, 1, 'asset', 'operating'),
    ('1002', '银行存款', None, 1, 'asset', 'operating'),
    ('1012', '其他货币资金', None, 1, 'asset', 'operating'),
    ('1101', '交易性金融资产', None, 1, 'asset', 'investing'),
    ('1122', '应收账款', None, 1, 'asset', 'operating'),
    ('1123', '预付账款', None, 1, 'asset', 'operating'),
    ('1131', '应收股利', None, 1, 'asset', 'investing'),
    ('1221', '其他应收款', None, 1, 'asset', 'operating'),
    ('1405', '库存商品', None, 1, 'asset', 'operating'),
    ('1501', '持有至到期投资', None, 1, 'asset', 'investing'),
    ('1511', '长期股权投资', None, 1, 'asset', 'investing'),
    ('1601', '固定资产', None, 1, 'asset', 'operating'),
    ('1602', '累计折旧', '1601', 2, 'asset', 'operating'),
    ('1701', '无形资产', None, 1, 'asset', 'operating'),
    # ── 负债类 (category=liability) ──
    ('2001', '短期借款', None, 1, 'liability', 'financing'),
    ('2202', '应付账款', None, 1, 'liability', 'operating'),
    ('2203', '预收账款', None, 1, 'liability', 'operating'),
    ('2211', '应付职工薪酬', None, 1, 'liability', 'operating'),
    ('2221', '应交税费', None, 1, 'liability', 'operating'),
    ('2241', '其他应付款', None, 1, 'liability', 'operating'),
    ('2501', '长期借款', None, 1, 'liability', 'financing'),
    ('2502', '应付债券', None, 1, 'liability', 'financing'),
    # ── 所有者权益类 (category=equity) ──
    ('4001', '实收资本', None, 1, 'equity', 'equity'),
    ('4002', '资本公积', None, 1, 'equity', 'equity'),
    ('4103', '本年利润', None, 1, 'equity', 'equity'),
    ('4104', '利润分配', None, 1, 'equity', 'equity'),
]


def run():
    engine = get_engine()
    with engine.connect() as conn:
        inserted = 0
        for row in BALANCE_SHEET_SUBJECTS:
            res = conn.execute(text("""
                INSERT IGNORE INTO subjects (subject_code, subject_name, parent_code, level, category, new_standard_category, is_active)
                VALUES (:code, :name, :parent, :level, :cat, :ns_cat, 1)
            """), {"code": row[0], "name": row[1], "parent": row[2],
                   "level": row[3], "cat": row[4], "ns_cat": row[5]})
            inserted += res.rowcount
        conn.commit()
        logger.info(f"✅ 插入 {inserted} 条资产负债表科目（已有则跳过）")
        total = conn.execute(text("SELECT count(*) FROM subjects")).scalar()
        by_cat = conn.execute(text(
            "SELECT category, count(*) FROM subjects GROUP BY category ORDER BY category"
        )).fetchall()
        dist = {r[0]: r[1] for r in by_cat}
        logger.info(f"✅ subjects 表当前共 {total} 条，分类分布: {dist}")


if __name__ == "__main__":
    run()
