"""tdnet ライブラリ 使用例集。

uv run python samples/usage_examples.py で実行可能。
"""

from __future__ import annotations

# ============================================================
# 基本: 日付指定で開示一覧を取得
# ============================================================

import tdnet
from tdnet import CK, extract_values, extracted_to_dict

# 日付指定 (XBRL付きのみ)
filings = tdnet.documents("20260304", has_xbrl=True)
print(f"開示件数: {len(filings)}")
for f in filings[:5]:
    print(f"  {f.company_code} {f.company_name}: {f.title}")


# ============================================================
# 例1: 決算短信から主要財務指標を取得
# ============================================================

# 決算短信を1件取得してXBRLパース
kessan = [f for f in filings if "決算短信" in f.title][0]
stmts = kessan.xbrl()

# 当期・連結の主要指標を一括取得
result = extract_values(
    stmts,
    [CK.REVENUE, CK.OPERATING_INCOME, CK.NET_INCOME_PARENT,
     CK.TOTAL_ASSETS, CK.EPS, CK.ROE, CK.EQUITY_RATIO],
    period="current",
    consolidated=True,
)
row = extracted_to_dict(result)
print("\n--- 主要指標 ---")
for k, v in row.items():
    print(f"  {k}: {v}")


# ============================================================
# 例2: PL / BS / CF を網羅的に取得
# ============================================================

pl_keys = [
    CK.REVENUE, CK.COST_OF_SALES, CK.GROSS_PROFIT,
    CK.SGA_EXPENSES, CK.OPERATING_INCOME,
    CK.ORDINARY_INCOME, CK.NET_INCOME_PARENT,
]
bs_keys = [
    CK.TOTAL_ASSETS, CK.CURRENT_ASSETS, CK.NONCURRENT_ASSETS,
    CK.TOTAL_LIABILITIES, CK.NET_ASSETS,
    CK.CASH_AND_DEPOSITS, CK.INVENTORIES,
    CK.SHAREHOLDERS_EQUITY, CK.RETAINED_EARNINGS,
]
cf_keys = [
    CK.OPERATING_CF, CK.INVESTING_CF, CK.FINANCING_CF,
    CK.DEPRECIATION_CF, CK.PURCHASE_PPE_CF,
]

all_keys = pl_keys + bs_keys + cf_keys
result = extract_values(stmts, all_keys, period="current", consolidated=True)
row = extracted_to_dict(result)
print("\n--- PL/BS/CF ---")
for k, v in row.items():
    print(f"  {k}: {v}")


# ============================================================
# 例3: 前期比較
# ============================================================

current = extracted_to_dict(
    extract_values(stmts, [CK.REVENUE, CK.OPERATING_INCOME],
                   period="current", consolidated=True)
)
prior = extracted_to_dict(
    extract_values(stmts, [CK.REVENUE, CK.OPERATING_INCOME],
                   period="prior", consolidated=True)
)
print("\n--- 前期比較 ---")
for k in [CK.REVENUE, CK.OPERATING_INCOME]:
    c, p = current.get(k), prior.get(k)
    if c is not None and p is not None and p != 0:
        chg = (c - p) / abs(p) * 100
        print(f"  {k}: {p:>15,} → {c:>15,} ({chg:+.1f}%)")


# ============================================================
# 例4: 非連結（個別）決算の取得
# ============================================================

# 配当(DPS)は常に非連結
dps_result = extract_values(
    stmts, [CK.DPS, CK.INTERIM_DPS], period="current", consolidated=False,
)
print(f"\n--- 配当（非連結） ---")
for k, v in extracted_to_dict(dps_result).items():
    print(f"  {k}: {v}")


# ============================================================
# 例5: 全マッピング可能CKを自動抽出
# ============================================================

all_result = extract_values(stmts, period="current", consolidated=True)
print(f"\n--- 全自動抽出: {len(all_result)} CKs ---")
for k, ev in sorted(all_result.items())[:20]:
    print(f"  {k}: {ev.value}")


# ============================================================
# 例6: 証券コードで検索
# ============================================================

code_filings = tdnet.documents(code=7203, has_xbrl=True, limit=5)
print(f"\n--- 7203 (トヨタ) 直近: {len(code_filings)} 件 ---")
for f in code_filings:
    print(f"  {f.pubdate} {f.title}")


# ============================================================
# 例7: DataFrame / CSV出力
# ============================================================

df = stmts.to_dataframe()
print(f"\n--- DataFrame: {df.shape} ---")
print(df[["label_ja", "value", "local_name"]].head(5).to_string())

# CSV保存
# stmts.to_csv("output.csv")
# stmts.to_parquet("output.parquet")


# ============================================================
# 例8: 科目検索
# ============================================================

items = stmts.search("売上")
print(f"\n--- 「売上」検索: {len(items)} 件 ---")
for it in items[:5]:
    print(f"  {it.local_name}: {it.value}")


# ============================================================
# 例9: カスタムマッパーの追加
# ============================================================

# 独自の概念を追加マッピング
custom_mapper = tdnet.dict_mapper(
    {"GainOnSalesOfInvestmentSecuritiesEI": "custom_gain_investment_sales"},
    name="my_custom",
)
result = extract_values(
    stmts,
    ["custom_gain_investment_sales"],
    mapper=[tdnet.summary_mapper, tdnet.statement_mapper, custom_mapper],
)
print(f"\n--- カスタムマッパー ---")
for k, ev in result.items():
    val = ev.value if ev else "N/A"
    print(f"  {k}: {val}")


# ============================================================
# 例10: 複数銘柄を一括処理
# ============================================================

print("\n--- 一括処理 ---")
filings = tdnet.documents("20260304", has_xbrl=True)
for f in filings:
    if "決算短信" not in f.title:
        continue
    try:
        stmts = f.xbrl()
        result = extract_values(
            stmts,
            [CK.REVENUE, CK.OPERATING_INCOME, CK.NET_INCOME_PARENT],
            period="current",
            consolidated=True,
        )
        row = extracted_to_dict(result)
        rev = row.get(CK.REVENUE)
        oi = row.get(CK.OPERATING_INCOME)
        ni = row.get(CK.NET_INCOME_PARENT)
        # 非連結フォールバック
        if rev is None:
            row2 = extracted_to_dict(extract_values(
                stmts,
                [CK.REVENUE, CK.OPERATING_INCOME, CK.NET_INCOME_PARENT],
                period="current", consolidated=False,
            ))
            rev = rev or row2.get(CK.REVENUE)
            oi = oi or row2.get(CK.OPERATING_INCOME)
            ni = ni or row2.get(CK.NET_INCOME_PARENT)
        print(f"  {f.company_code} {f.company_name}: "
              f"売上={rev}, 営業利益={oi}, 純利益={ni}")
    except Exception as e:
        print(f"  {f.company_code} {f.company_name}: ERROR - {e}")
