# -*- coding: utf-8 -*-
r"""브리프 06 — 혼자 사는 경기 청년은 2022년에 정점을 찍었다 (2015~2025)

    py prep.py

왜 이 브리프인가
  주간 이슈 보드가 **DT_1PL1502 에 2025년 자료가 들어왔다**고 알렸다(2024 → 2025).
  B02·B03 은 2024 까지만 봤다. 한 해를 더 붙이자 이야기가 뒤집혔다.

  ★ **B02 는 두 시점(2015·2024)만 비교했다.** 그래서 중간의 전환점을 못 봤다.
    실제로 20~29세 1인가구는 **2022년이 정점**이고 그 뒤 3년 연속 줄고 있다.
    「9년새 73% 늘었다」는 틀린 말이 아니지만, 그 문장만으로는 지금 무슨 일이
    일어나는지 알 수 없다. 이 브리프는 그 정정이다.

쓰는 표
  DT_1PL1502  성 및 연령별 1인가구 - 시군구   2015~2025 · 지역prefix 31 · 항목 T00(계)

★ 연령 라벨에 「80~84」만 '세'가 빠져 있다 (다른 칸은 '80~84세' 형식). 라벨로 다루므로 그대로 쓴다.
"""
import csv, sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import kosis

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# ⛔ 그림 저장은 정본(`chartkit.save`)을 지난다 〔2026-09-21〕 — 그래야
#   ⑴ 폰용 그림이 같이 나가고(`analysis/폰/`) ⑵ 「폰에서 읽히나」 관문이 돈다.
#   `plt.savefig` 를 직접 부르면 그 둘이 통째로 꺼진다.
import chartkit as ck

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

plt.rcParams["font.family"] = ["Malgun Gothic", "sans-serif"]
plt.rcParams["axes.unicode_minus"] = False

ORG, TBL, ITM = "101", "DT_1PL1502", "T00"
Y0, Y1 = "2015", "2025"
YOUNG = ["20~24세", "25~29세"]
MID30 = ["30~34세"]
OLD = ["65~69세", "70~74세", "75~79세", "80~84", "85세이상"]      # ★ '80~84' 는 '세' 없음
C_Y, C_O, C_M = "#c8482a", "#2f6fb5", "#8b95a1"

rec = kosis.fetch_rows(ORG, TBL, (Y0, Y1), sel={"A": ["경기도"], "B": ["합계"] + YOUNG + MID30 + OLD},
                       prefix={"A": "31"}, itm=ITM)
d = {}
for r in rec:
    d.setdefault(r["연도"], {})[r["B"]] = r["값"]
yrs = sorted(d)
print(f"[대장] 원문위치 → {kosis.cite(ORG, TBL, 'A', ['경기도'], '31')}")
print(f"[대장] 청년 연령 → {kosis.cite(ORG, TBL, 'B', YOUNG, None)}")
print(f"[대장] 노년 연령 → {kosis.cite(ORG, TBL, 'B', OLD, None)}")

g = lambda y, ks: sum(d[y][k] for k in ks)
young = {y: g(y, YOUNG) for y in yrs}
old = {y: g(y, OLD) for y in yrs}
mid = {y: g(y, MID30) for y in yrs}
tot = {y: d[y]["합계"] for y in yrs}

peak = max(yrs, key=lambda y: young[y])
줄어든해 = [y for i, y in enumerate(yrs[1:], 1) if young[y] < young[yrs[i - 1]]]
연속감소 = 0
for y in reversed(yrs[1:]):
    if young[y] < young[yrs[yrs.index(y) - 1]]:
        연속감소 += 1
    else:
        break

rows = [{"연도": y, "구분": k, "값": v[y]}
        for k, v in (("20~29세", young), ("30~34세", mid), ("65세이상", old), ("합계", tot))
        for y in yrs]
with open("raw.csv", "w", encoding="utf-8-sig", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["연도", "구분", "값"])
    w.writeheader(); w.writerows(rows)

# ── 차트(웹) ── 같은 그림에 두 방향을 겹친다. 2015=100 으로 맞춰야 규모 차이에 묻히지 않는다
fig, ax = plt.subplots(figsize=(7.6, 6.6))
xs = [int(y) for y in yrs]
for nm, v, c, lw in (("65세 이상", old, C_O, 3.0), ("30~34세", mid, C_M, 2.2), ("20~29세", young, C_Y, 3.4)):
    ax.plot(xs, [100 * v[y] / v[Y0] for y in yrs], color=c, lw=lw, label=nm, zorder=3)
    ax.text(xs[-1] + .12, 100 * v[yrs[-1]] / v[Y0], f" {nm}", color=c, fontsize=10.5,
            fontweight="bold", va="center")
ax.axvline(int(peak), color=C_Y, ls=":", lw=1.4, zorder=1)
ax.annotate(f"{peak} 정점", (int(peak), 100 * young[peak] / young[Y0]),
            xytext=(-6, 14), textcoords="offset points", color=C_Y,
            fontsize=10.5, fontweight="bold", ha="right")
ax.set_title("경기 1인가구 — 청년은 2022년에 꺾였고, 노년은 한 번도 줄지 않았다\n"
             f"{Y0}년=100 기준", fontsize=12.5, fontweight="bold", loc="left", pad=14)
ax.set_ylabel(f"{Y0}년 = 100", fontsize=10.5)
ax.grid(axis="y", color="#eef0f4", lw=.9)
ax.set_axisbelow(True)
ax.set_xlim(xs[0] - .3, xs[-1] + 1.9)
for s in ("top", "right", "left"):
    ax.spines[s].set_visible(False)
ax.spines["bottom"].set_color("#cfd4de")
fig.tight_layout()
ck.save(fig, "chart.png", dpi=130)
plt.close(fig)

# ── 카드 ── 폰. 청년만 실수로 보여준다(지수는 카드에서 오해를 부른다)
fig, ax = plt.subplots(figsize=(8.4, 6.0))
ax.bar(xs, [young[y] / 10000 for y in yrs],
       color=[C_Y if y >= peak else "#e6b3a6" for y in yrs], width=.68)
ax.axvline(int(peak) + .5, color="#14181d", lw=1.2, ls="--")
ax.text(int(peak) + .65, max(young.values()) / 10000 * .96,
        f"  {peak} 정점 이후\n  3년 연속 감소", fontsize=12, fontweight="bold", va="top")
ax.set_title("혼자 사는 경기 20대는 줄고 있다", fontsize=16, fontweight="bold", loc="left", pad=12)
ax.set_ylabel("20~29세 1인가구 (만 가구)", fontsize=11.5)
ax.grid(axis="y", color="#eef0f4", lw=.9)
ax.set_axisbelow(True)
for s in ("top", "right", "left"):
    ax.spines[s].set_visible(False)
ax.spines["bottom"].set_color("#cfd4de")
fig.tight_layout()
fig.savefig("chart_card.png", dpi=130)
plt.close(fig)

print(f"[저장] raw.csv {len(rows)}행 · chart.png · chart_card.png")

print("\n[대장] 수치대장.csv 에 옮길 값 ─────────────────")
print(f"  합계_{Y0}                {tot[Y0]:,}")
print(f"  합계_2024               {tot['2024']:,}")
print(f"  합계_{Y1}                {tot[Y1]:,}")
print(f"  합계증가율_15_24         {100*(tot['2024']/tot[Y0]-1):.1f} %   ← B02 가 쓴 값")
print(f"  합계증가율_15_25         {100*(tot[Y1]/tot[Y0]-1):.1f} %")
print(f"  청년_{Y0}                {young[Y0]:,}")
print(f"  청년_정점{peak}           {young[peak]:,}")
print(f"  청년_{Y1}                {young[Y1]:,}")
print(f"  청년정점대비감소          {young[peak]-young[Y1]:,} 가구")
print(f"  청년정점대비감소율        {100*(young[Y1]/young[peak]-1):.1f} %")
print(f"  청년연속감소연수          {연속감소}")
print(f"  청년증가율_15_25          {100*(young[Y1]/young[Y0]-1):.1f} %")
print(f"  노년_{Y0}                {old[Y0]:,}")
print(f"  노년_{Y1}                {old[Y1]:,}")
print(f"  노년증가율_15_25          {100*(old[Y1]/old[Y0]-1):.1f} %")
print(f"  노년감소연수             0")
print(f"  삼십대초_{Y1}             {mid[Y1]:,}  (증가율 {100*(mid[Y1]/mid[Y0]-1):.1f}%)")
print(f"  청년감소해               {', '.join(줄어든해)}")
