import csv
import io
import json
import pandas as pd
import sys
from dateutil import tz
from datetime import datetime, date, time, timedelta

# Japan Standard Time (UTC + 09:00)
JST = tz.gettz('Asia/Tokyo')
JST_current_time = datetime.now(tz=JST).strftime('%Y/%m/%d %H:%M')


patients_list = []
patients_summary_dic = {}

# 引数を取得 異常系処理はしてないので注意
args = sys.argv

with open('data/patients.csv', 'r', encoding="utf-8") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        patients_list.append(row)
        patients_summary_dic.setdefault(row['date'], 0)
        patients_summary_dic[row['date']] += 1

# 日付のリストを生成
strdt = datetime.strptime("2020-01-26", '%Y-%m-%d')  # 開始日
enddt = datetime.strptime(args[1], '%Y-%m-%d')  # 終了日

# 日付差の日数を算出（リストに最終日も含めたいので、＋１しています）
days_num = (enddt - strdt).days + 1

datelist = []
for i in range(days_num):
    datelist.append(strdt + timedelta(days = i))

patients_summary_list = []

# 日付の新しい順に辿って小計が 0 でない日から開始する
foundZero = True
for date in reversed(datelist):
    if (not (date.strftime('%Y-%m-%d') in patients_summary_dic)) and foundZero:
        continue
    else:
        foundZero = False
        patients_summary_dic.setdefault(date.strftime('%Y-%m-%d'), 0)
        patients_summary_list.append({
            "日付": date.strftime('%Y-%m-%d'),
            "小計": patients_summary_dic[date.strftime('%Y-%m-%d')]
        })

patients_summary_list = patients_summary_list[::-1] # 日付の昇順に並び替え


# main_summary_history.csvをPandasのDataframeに変換
main_summary_history_df = pd.read_csv('data/main_summary_history.csv', keep_default_na=False)

# 検査件数の読み込み
inspections_summary_list = []
with open('data/inspections_summary.csv', 'r', encoding="utf-8") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        inspections_summary_list.append({
            "日付": datetime.strptime(row['検査日'], '%Y/%m/%d').strftime('%Y-%m-%d'),
            "小計": int(row['検査件数（件）']),
            "合算": row['合算']
        })

data = {
    "lastUpdate": JST_current_time,
    "patients": {
        "date": JST_current_time,
        "data": patients_list
    },
    "patients_summary" : {
        "date": JST_current_time,
        "data": patients_summary_list
    },
    "inspections_summary" : {
        "date": JST_current_time,
        "data": inspections_summary_list
    },
    "main_summary_history": {
        "date": JST_current_time,
        "data": json.loads(main_summary_history_df.to_json(orient='records', force_ascii=False))
    }
}

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
print(json.dumps(data, indent=4, ensure_ascii=False))

[((184, 206), 'dateutil.tz.gettz', 'tz.gettz', (['"""Asia/Tokyo"""'], {}), "('Asia/Tokyo')\n", (192, 206), False, 'from dateutil import tz\n'), ((646, 689), 'datetime.datetime.strptime', 'datetime.strptime', (['"""2020-01-26"""', '"""%Y-%m-%d"""'], {}), "('2020-01-26', '%Y-%m-%d')\n", (663, 689), False, 'from datetime import datetime, date, time, timedelta\n'), ((705, 743), 'datetime.datetime.strptime', 'datetime.strptime', (['args[1]', '"""%Y-%m-%d"""'], {}), "(args[1], '%Y-%m-%d')\n", (722, 743), False, 'from datetime import datetime, date, time, timedelta\n'), ((1527, 1594), 'pandas.read_csv', 'pd.read_csv', (['"""data/main_summary_history.csv"""'], {'keep_default_na': '(False)'}), "('data/main_summary_history.csv', keep_default_na=False)\n", (1538, 1594), True, 'import pandas as pd\n'), ((2513, 2566), 'io.TextIOWrapper', 'io.TextIOWrapper', (['sys.stdout.buffer'], {'encoding': '"""utf-8"""'}), "(sys.stdout.buffer, encoding='utf-8')\n", (2529, 2566), False, 'import io\n'), ((441, 464), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {}), '(csvfile)\n', (455, 464), False, 'import csv\n'), ((1728, 1751), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {}), '(csvfile)\n', (1742, 1751), False, 'import csv\n'), ((2573, 2619), 'json.dumps', 'json.dumps', (['data'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(data, indent=4, ensure_ascii=False)\n', (2583, 2619), False, 'import json\n'), ((226, 246), 'datetime.datetime.now', 'datetime.now', ([], {'tz': 'JST'}), '(tz=JST)\n', (238, 246), False, 'from datetime import datetime, date, time, timedelta\n'), ((893, 910), 'datetime.timedelta', 'timedelta', ([], {'days': 'i'}), '(days=i)\n', (902, 910), False, 'from datetime import datetime, date, time, timedelta\n'), ((1195, 1220), 'datetime.date.strftime', 'date.strftime', (['"""%Y-%m-%d"""'], {}), "('%Y-%m-%d')\n", (1208, 1220), False, 'from datetime import datetime, date, time, timedelta\n'), ((1035, 1060), 'datetime.date.strftime', 'date.strftime', (['"""%Y-%m-%d"""'], {}), "('%Y-%m-%d')\n", (1048, 1060), False, 'from datetime import datetime, date, time, timedelta\n'), ((1286, 1311), 'datetime.date.strftime', 'date.strftime', (['"""%Y-%m-%d"""'], {}), "('%Y-%m-%d')\n", (1299, 1311), False, 'from datetime import datetime, date, time, timedelta\n'), ((1352, 1377), 'datetime.date.strftime', 'date.strftime', (['"""%Y-%m-%d"""'], {}), "('%Y-%m-%d')\n", (1365, 1377), False, 'from datetime import datetime, date, time, timedelta\n'), ((1839, 1880), 'datetime.datetime.strptime', 'datetime.strptime', (["row['検査日']", '"""%Y/%m/%d"""'], {}), "(row['検査日'], '%Y/%m/%d')\n", (1856, 1880), False, 'from datetime import datetime, date, time, timedelta\n')]