#!/usr/bin/env python3
"""Create the reproducible portfolio-analysis notebook."""

from pathlib import Path

import nbformat as nbf


ROOT = Path(__file__).resolve().parent
NOTEBOOK = ROOT / "smart-canteen-28-project-usage-analysis.ipynb"


def main() -> None:
    notebook = nbf.v4.new_notebook()
    notebook["metadata"]["kernelspec"] = {"display_name": "Python 3", "language": "python", "name": "python3"}
    notebook["metadata"]["language_info"] = {"name": "python", "version": "3"}
    notebook["cells"] = [
        nbf.v4.new_markdown_cell("""# 28个智慧食堂项目功能使用分析

## tl;dr

- 历史线程里的“28”是28个在途事项，不是权威客户项目数。本分析重建28个候选：20个中央统计项目、5个近期独立项目、3个规划项目。
- 17个数据库注册项目中，本次12个可连接、5个不可达；12个可连接项目中7个近30天有有效订单。
- 7个有单项目合计445,164单、项目活跃用户之和16,089、订单流水¥7,035,219.63；消费机占91.9%。
- 金斯瑞、机场、赛迪贡献97.5%的订单。非交易功能中取餐流程、取餐柜接口、后台审计、卡片、退款和报表有明确记录；健康与AI功能信号很弱。
- 中央统计同期203,990单，低于生产库直连445,164单，不能替代直连用量判断。"""),
        nbf.v4.new_markdown_cell("""## Context & Methods

### Key Assumptions

- 报告日为2026-08-03，排除2026-08-04未完整当日。
- 有效订单优先使用`pay_status=20`、`order_status=30`、`is_delete=0`、`user_id>0`，按`meal_date`归属；字段不存在时按项目表结构降级。
- 当前窗口为2026-07-05至2026-08-03，前一窗口为2026-06-05至2026-07-04。
- 不可达、未映射与零记录分开；业务表记录不等于页面点击或独立用户。
- 仅持久化项目级聚合，不保存凭据、个人信息、订单明细或原始生产payload。"""),
        nbf.v4.new_code_cell("""from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt

ROOT = Path.cwd()
master = pd.read_csv(ROOT / 'project-master.csv')
cards = pd.read_csv(ROOT / 'project-usage-cards.csv')
portfolio = pd.read_csv(ROOT / 'portfolio-summary.csv')
project_rank = pd.read_csv(ROOT / 'project-order-ranking.csv')
channel_rank = pd.read_csv(ROOT / 'channel-ranking.csv')
feature_rank = pd.read_csv(ROOT / 'feature-ranking.csv')
central = pd.read_csv(ROOT / 'central-project-summary.csv')
db_core = pd.read_csv(ROOT / 'db-project-status.csv')

len(master), len(central), len(db_core)"""),
        nbf.v4.new_markdown_cell("## Results\n\n### 1. 项目覆盖与数据可核验性"),
        nbf.v4.new_code_cell("""portfolio"""),
        nbf.v4.new_code_cell("""coverage = pd.DataFrame({
    '层级': ['重建候选','中央登记','数据库注册','数据库可连接','近30天有订单'],
    '项目数': [28,20,17,12,7],
})
ax = coverage.plot.bar(x='层级', y='项目数', legend=False, figsize=(8,4), color='#1769aa')
ax.set_title('项目覆盖漏斗')
ax.set_ylabel('项目数')
ax.grid(axis='y', alpha=.2)
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()"""),
        nbf.v4.new_markdown_cell("### 2. 哪些项目贡献真实用量"),
        nbf.v4.new_code_cell("""rank = project_rank.sort_values('orders')
ax = rank.plot.barh(x='project', y='orders', legend=False, figsize=(9,4.8), color='#1769aa')
ax.set_title('近30天有效订单')
ax.set_xlabel('订单数')
ax.set_ylabel('')
ax.grid(axis='x', alpha=.2)
plt.tight_layout()
plt.show()
project_rank"""),
        nbf.v4.new_markdown_cell("### 3. 哪些功能入口使用最多"),
        nbf.v4.new_code_cell("""channels = channel_rank.sort_values('orders')
ax = channels.plot.barh(x='channel', y='orders', legend=False, figsize=(9,4.8), color='#2980b9')
ax.set_title('近30天功能入口订单')
ax.set_xlabel('订单数')
ax.set_ylabel('')
ax.grid(axis='x', alpha=.2)
plt.tight_layout()
plt.show()
channel_rank"""),
        nbf.v4.new_markdown_cell("### 4. 非交易功能业务信号"),
        nbf.v4.new_code_cell("""signals = feature_rank.head(10).sort_values('records')
ax = signals.plot.barh(x='feature', y='records', legend=False, figsize=(9,5.2), color='#4f9bd3')
ax.set_title('近30天非交易功能业务记录')
ax.set_xlabel('记录数（不是用户数）')
ax.set_ylabel('')
ax.grid(axis='x', alpha=.2)
plt.tight_layout()
plt.show()
feature_rank"""),
        nbf.v4.new_markdown_cell("### 5. 中央统计与直连生产库差异"),
        nbf.v4.new_code_cell("""direct_orders = int(project_rank.orders.sum())
central_orders = int(central.current30_orders.sum())
pd.DataFrame([{
    '生产库直连订单': direct_orders,
    '中央统计订单': central_orders,
    '中央少计': direct_orders-central_orders,
    '中央/直连': central_orders/direct_orders,
}])"""),
        nbf.v4.new_markdown_cell("""## Takeaways

1. **产品主战场仍是交易核心。** 消费机是跨项目绝对主入口；高频项目的稳定性、外部订单一致性、取餐与报表自动化应优先于继续堆叠低激活功能。
2. **项目画像必须分开运营。** 金斯瑞是消费机+取餐柜，机场是消费机+外部订单，赛迪是消费机+闸机+卡/规则，产业园是绑盘+虚拟订单，西康是绑盘。
3. **健康与AI能力尚未形成跨项目使用。** 可见业务记录很少；要评价渗透率必须补页面、小程序、设备和接口事件流。
4. **先修数据基础再做全局经营看板。** 当前中央统计少计241,174单，且前30天活跃用户返回0；在修复前不宜用中央统计评价项目增减和功能采用。
5. **28候选表应转为正式项目主数据。** 需要唯一项目ID，以及客户、仓库、部署、中央项目码、数据库、线程任务的映射关系。"""),
    ]
    nbf.write(notebook, NOTEBOOK)
    print(NOTEBOOK)


if __name__ == "__main__":
    main()
