"""
general_analysis HTML 요약 리포트.
"""

from __future__ import annotations

from pathlib import Path

import pandas as pd

from deepcoin.analysis.general_analysis_config import DEFAULT_OUTPUT_CSV, DEFAULT_OUTPUT_HTML


def write_analysis_report(
    csv_path: Path | str = DEFAULT_OUTPUT_CSV,
    html_path: Path | str = DEFAULT_OUTPUT_HTML,
) -> Path:
    """
    스냅샷 CSV를 읽어 모듈별 컬럼 수·샘플 테이블 HTML 생성.

    Returns:
        HTML 경로.
    """
    df = pd.read_csv(csv_path)
    html_out = Path(html_path)
    html_out.parent.mkdir(parents=True, exist_ok=True)

    modules = {
        "지표 (ga_)": [c for c in df.columns if "_ga_" in c or c.startswith("ga_")],
        "패턴": [c for c in df.columns if "ga_pattern_" in c],
        "파동·구조": [c for c in df.columns if "ga_struct_" in c or "ga_elliott" in c or "ga_wyckoff" in c or "ga_fib_" in c],
        "차트": [c for c in df.columns if "ga_chart_" in c],
        "MTF 합성": [c for c in df.columns if "ga_align_" in c],
        "레거시": [c for c in df.columns if c.endswith("_RSI") or c.endswith("_bb_pos")],
    }

    summary_rows = ""
    for name, cols in modules.items():
        summary_rows += f"<tr><td>{name}</td><td>{len(cols)}</td></tr>"

    sample = df.head(5)[
        ["dt", "action", "price", "ga_align_timing_buy_score", "ga_align_mtf_conflict", "d1_RSI", "m3_RSI"]
    ].to_html(index=False, classes="tbl") if "d1_RSI" in df.columns else df.head(3).to_html(index=False)

    buy_mean = df[df["action"] == "buy"]["ga_align_timing_buy_score"].mean() if "ga_align_timing_buy_score" in df.columns else 0
    sell_mean = df[df["action"] == "sell"]["ga_align_timing_sell_score"].mean() if "ga_align_timing_sell_score" in df.columns else 0

    content = f"""<!DOCTYPE html>
<html lang="ko"><head><meta charset="utf-8"/>
<title>general_analysis 실행 리포트</title>
<style>
body {{ font-family: "Malgun Gothic", Arial, sans-serif; margin: 24px; background: #f5f5f5; }}
table.tbl {{ border-collapse: collapse; width: 100%; background: #fff; font-size: 0.85rem; }}
th, td {{ border: 1px solid #e2e8f0; padding: 6px 8px; }}
th {{ background: #e2e8f0; }}
</style></head><body>
<h1>general_analysis 실행 리포트</h1>
<p>타점 {len(df)}건 · 컬럼 {len(df.columns)}개 · CSV: {csv_path}</p>
<h2>모듈별 컬럼 수</h2>
<table class="tbl"><thead><tr><th>모듈</th><th>컬럼 수</th></tr></thead>
<tbody>{summary_rows}</tbody></table>
<h2>MTF 합성 평균</h2>
<ul>
<li>매수 타점 timing_buy_score 평균: {buy_mean:.3f}</li>
<li>매도 타점 timing_sell_score 평균: {sell_mean:.3f}</li>
</ul>
<h2>샘플 5건</h2>
{sample}
<p>전체 데이터: <code>{csv_path}</code></p>
</body></html>"""
    html_out.write_text(content, encoding="utf-8")
    print(f"리포트: {html_out}")
    return html_out
