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36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
"""리포트 νƒ­ 곡톡 μœ ν‹Έλ¦¬ν‹°.

Feature별 미리보기, HTML 생성, CSV λ³€ν™˜ λ“± 곡톡 ν•¨μˆ˜.
"""
import io
import csv

import pandas as pd
import requests
import streamlit as st
import streamlit.components.v1 as components

from core.api_client import ChainShiftClient


def render_feature_section(
    client: ChainShiftClient,
    campaign_id: int,
    feature_key: str,
    title: str,
    description: str,
    start_date: str,
    end_date: str,
    api_key: str = "",
    access_token: str = "",
):
    """단일 Feature μ„Ήμ…˜ λ Œλ”λ§."""
    html_state_key = f"html_content_{feature_key}_{campaign_id}"
    insights_key = f"insights_enabled_{feature_key}_{campaign_id}"

    with st.container(border=True):
        # Header
        c1, c2 = st.columns([4, 1])
        with c1:
            st.markdown(f"**{title}**")
            st.caption(description)

        # Preview Section (Lazy loaded)
        with st.expander(f"πŸ‘οΈ 미리보기", expanded=False):
            try:
                result = get_report_feature_data(api_key, campaign_id, feature_key, start_date, end_date, access_token=access_token)
                if result.get("success"):
                    data = result.get("data", {})
                    render_feature_preview(feature_key, data)
                else:
                    st.warning(f"데이터 λ‘œλ“œ μ‹€νŒ¨: {result.get('error', 'Unknown')}")
            except Exception as e:
                st.error(f"미리보기 였λ₯˜: {e}")

        # LLM Insights checkbox
        enable_insights = st.checkbox(
            "πŸ€– LLM μΈμ‚¬μ΄νŠΈ 포함",
            value=st.session_state.get(insights_key, True),
            key=f"insights_cb_{feature_key}",
            help="μ»¨μ„€ν„΄νŠΈ ν†€μ˜ 뢄석 μ½”λ©˜νŠΈλ₯Ό μΆ”κ°€ν•©λ‹ˆλ‹€",
        )
        st.session_state[insights_key] = enable_insights

        # Generated HTML display section
        if html_state_key in st.session_state:
            html_data = st.session_state[html_state_key]
            html_content = html_data.get("content", "")
            html_url = html_data.get("url", "")

            st.success(f"βœ… HTML 리포트 생성 μ™„λ£Œ" + (" (LLM μΈμ‚¬μ΄νŠΈ 포함)" if html_data.get("insights") else ""))

            if html_content:
                # Action buttons
                col_open, col_dl, col_csv, col_reset = st.columns(4)

                with col_open:
                    if html_url:
                        st.link_button("πŸ”— μƒˆ μ°½μ—μ„œ 보기", html_url, use_container_width=True)
                    else:
                        st.button("πŸ”— μƒˆ μ°½μ—μ„œ 보기", disabled=True, use_container_width=True, key=f"html_open_{feature_key}_disabled")

                with col_dl:
                    st.download_button(
                        label="πŸ“₯ HTML λ‹€μš΄λ‘œλ“œ",
                        data=b'\xef\xbb\xbf' + html_content.lstrip('\ufeff').encode("utf-8"),
                        file_name=f"{feature_key}_{campaign_id}_{start_date}_{end_date}.html",
                        mime="text/html; charset=utf-8",
                        use_container_width=True,
                        key=f"html_dl_{feature_key}",
                    )

                with col_csv:
                    try:
                        result = get_report_feature_data(api_key, campaign_id, feature_key, start_date, end_date, access_token=access_token)
                        if result.get("success"):
                            csv_data = convert_report_data_to_csv(feature_key, result.get("data", {}))
                            st.download_button(
                                label="πŸ“Š CSV λ‹€μš΄λ‘œλ“œ",
                                data=csv_data.encode("utf-8-sig"),
                                file_name=f"{feature_key}_{campaign_id}_{start_date}_{end_date}.csv",
                                mime="text/csv",
                                use_container_width=True,
                                key=f"csv_{feature_key}_post",
                            )
                        else:
                            st.button("πŸ“Š CSV λ‹€μš΄λ‘œλ“œ", disabled=True, use_container_width=True, key=f"csv_{feature_key}_post_disabled")
                    except Exception:
                        st.button("πŸ“Š CSV λ‹€μš΄λ‘œλ“œ", disabled=True, use_container_width=True, key=f"csv_{feature_key}_post_error")

                with col_reset:
                    if st.button("πŸ”„ λ‹€μ‹œ 생성", key=f"html_reset_{feature_key}", use_container_width=True):
                        del st.session_state[html_state_key]
                        st.rerun()

                # Inline preview
                with st.expander("πŸ‘οΈ HTML 미리보기", expanded=False):
                    components.html(html_content, height=500, scrolling=True)

            elif html_url:
                # Fallback: HTML download failed, show direct link
                col_link, col_csv, col_reset = st.columns(3)
                with col_link:
                    st.link_button("πŸ”— 리포트 μ—΄κΈ° (μ™ΈλΆ€ 링크)", html_url, use_container_width=True)
                with col_csv:
                    try:
                        result = get_report_feature_data(api_key, campaign_id, feature_key, start_date, end_date, access_token=access_token)
                        if result.get("success"):
                            csv_data = convert_report_data_to_csv(feature_key, result.get("data", {}))
                            st.download_button(
                                label="πŸ“Š CSV λ‹€μš΄λ‘œλ“œ",
                                data=csv_data.encode("utf-8-sig"),
                                file_name=f"{feature_key}_{campaign_id}_{start_date}_{end_date}.csv",
                                mime="text/csv",
                                use_container_width=True,
                                key=f"csv_{feature_key}_fallback",
                            )
                        else:
                            st.button("πŸ“Š CSV λ‹€μš΄λ‘œλ“œ", disabled=True, use_container_width=True, key=f"csv_{feature_key}_fallback_disabled")
                    except Exception:
                        st.button("πŸ“Š CSV λ‹€μš΄λ‘œλ“œ", disabled=True, use_container_width=True, key=f"csv_{feature_key}_fallback_error")
                with col_reset:
                    if st.button("πŸ”„ λ‹€μ‹œ 생성", key=f"html_reset_{feature_key}", use_container_width=True):
                        del st.session_state[html_state_key]
                        st.rerun()

        else:
            # Generate button
            col_html, col_csv = st.columns(2)

            with col_html:
                if st.button(f"πŸ“„ HTML 생성", key=f"html_{feature_key}", use_container_width=True):
                    spinner_text = "HTML 생성 쀑..." + (" (LLM μΈμ‚¬μ΄νŠΈ 포함)" if enable_insights else "")
                    with st.spinner(spinner_text):
                        try:
                            # Use url mode to avoid Vercel 4.5MB response limit.
                            # Download HTML from Supabase Storage directly.
                            result_url = client.generate_html_report(
                                campaign_id=campaign_id,
                                start_date=start_date,
                                end_date=end_date,
                                features=[feature_key],
                                enable_insights=enable_insights,
                                output_mode="url",
                            )
                            if result_url.get("success"):
                                data = result_url.get("data") or {}
                                html_url = data.get("html_url", "") if isinstance(data, dict) else ""
                                html_content = ""
                                if html_url:
                                    try:
                                        dl_resp = requests.get(html_url, timeout=30)
                                        dl_resp.raise_for_status()
                                        dl_resp.encoding = "utf-8"
                                        html_content = dl_resp.text
                                    except Exception as dl_err:
                                        st.warning(f"HTML λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨, URL 링크둜 λŒ€μ²΄: {dl_err}")
                                if not html_url and not html_content:
                                    st.error("HTML 생성 μ‹€νŒ¨: μŠ€ν† λ¦¬μ§€ URL이 λ°˜ν™˜λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
                                else:
                                    st.session_state[html_state_key] = {
                                        "content": html_content,
                                        "url": html_url,
                                        "insights": enable_insights,
                                    }
                                    st.rerun()
                            else:
                                st.error("HTML 생성 μ‹€νŒ¨: " + str(result_url.get("error", "Unknown")))
                        except Exception as e:
                            st.error(f"였λ₯˜: {e}")

            with col_csv:
                try:
                    result = get_report_feature_data(api_key, campaign_id, feature_key, start_date, end_date, access_token=access_token)
                    if result.get("success"):
                        csv_data = convert_report_data_to_csv(feature_key, result.get("data", {}))
                        st.download_button(
                            label="πŸ“Š CSV λ‹€μš΄λ‘œλ“œ",
                            data=csv_data.encode("utf-8-sig"),
                            file_name=f"{feature_key}_{campaign_id}_{start_date}_{end_date}.csv",
                            mime="text/csv",
                            use_container_width=True,
                            key=f"csv_{feature_key}",
                        )
                    else:
                        st.button("πŸ“Š CSV λ‹€μš΄λ‘œλ“œ", disabled=True, use_container_width=True, key=f"csv_{feature_key}_disabled")
                except Exception:
                    st.button("πŸ“Š CSV λ‹€μš΄λ‘œλ“œ", disabled=True, use_container_width=True, key=f"csv_{feature_key}_error")


def render_feature_preview(feature_key: str, data: dict):
    """Feature별 미리보기 μ‹œκ°ν™”."""
    if feature_key == "overview":
        cols = st.columns(4)
        with cols[0]:
            st.metric("총 질문 수", data.get("total_tasks", 0))
        with cols[1]:
            st.metric("총 λ‹΅λ³€ 수", data.get("total_answers", 0))
        with cols[2]:
            st.metric("κ°€μ‹œμ„±", f"{data.get('overall_visibility_pct', 0):.1f}%")
        with cols[3]:
            dr = data.get("date_range", {})
            period = f"{dr.get('start', '?')} ~ {dr.get('end', '?')}"
            st.metric("뢄석 κΈ°κ°„", period[:20])

    elif feature_key == "visibility":
        platforms = data.get("platforms", [])
        if platforms:
            rows = []
            for p in platforms:
                for b in p.get("brands", []):
                    rows.append({
                        "ν”Œλž«νΌ": p.get("platform", ""),
                        "λΈŒλžœλ“œ": b.get("brand_name", ""),
                        "κ°€μ‹œμ„± (%)": b.get("visibility_pct", 0),
                    })
            if rows:
                df = pd.DataFrame(rows)
                st.dataframe(df, use_container_width=True, hide_index=True)
        else:
            st.info("ν”Œλž«νΌ 데이터 μ—†μŒ")

    elif feature_key == "citations":
        sources = data.get("sources", [])[:10]
        if sources:
            df = pd.DataFrame(sources)
            cols = [c for c in ["source_host_url", "total_citations", "pct_of_total"] if c in df.columns]
            if cols:
                st.dataframe(df[cols], use_container_width=True, hide_index=True)
        else:
            st.info("인용 데이터 μ—†μŒ")

    elif feature_key == "citation-trends":
        sources = data.get("sources", [])
        if sources:
            rows = []
            for s in sources:
                for pt in s.get("trend", []):
                    rows.append({
                        "date": pt.get("task_date", ""),
                        "source": s.get("source_host_url", ""),
                        "citations": pt.get("citation_count", 0),
                    })
            if rows:
                df = pd.DataFrame(rows)
                pivot = df.pivot_table(index="date", columns="source", values="citations", aggfunc="sum").fillna(0)
                st.line_chart(pivot)
        else:
            st.info("μ‹œκ³„μ—΄ 데이터 μ—†μŒ")

    elif feature_key == "content-types":
        types = data.get("content_types", [])
        if types:
            df = pd.DataFrame(types)
            if "content_type" in df.columns and "total_citations" in df.columns:
                st.bar_chart(df.set_index("content_type")["total_citations"])
        else:
            st.info("μ½˜ν…μΈ  μœ ν˜• 데이터 μ—†μŒ")

    elif feature_key == "sentiment":
        in_house = data.get("in_house_brands", [])
        competitor = data.get("competitor_brands", [])

        if in_house:
            st.markdown("**🏒 μžμ‚¬ λΈŒλžœλ“œ**")
            df_ih = pd.DataFrame(in_house)
            cols_ih = ["brand_name", "total_mentions", "positive_rate", "negative_rate"]
            cols_ih = [c for c in cols_ih if c in df_ih.columns]
            if cols_ih:
                st.dataframe(df_ih[cols_ih], use_container_width=True, hide_index=True)

        if competitor:
            st.markdown("**🎯 κ²½μŸμ‚¬ λΈŒλžœλ“œ**")
            df_comp = pd.DataFrame(competitor)
            cols_comp = ["brand_name", "total_mentions", "positive_rate", "negative_rate"]
            cols_comp = [c for c in cols_comp if c in df_comp.columns]
            if cols_comp:
                st.dataframe(df_comp[cols_comp], use_container_width=True, hide_index=True)

        if not in_house and not competitor:
            brands = data.get("brands", [])
            if brands:
                df = pd.DataFrame(brands)
                cols = [c for c in ["brand_name", "brand_type", "positive_rate", "negative_rate"] if c in df.columns]
                if cols:
                    st.dataframe(df[cols], use_container_width=True, hide_index=True)
            else:
                st.info("감정 뢄석 데이터 μ—†μŒ")

    elif feature_key == "homepage-citations":
        daily_data = data.get("daily_data", [])[:10]
        if daily_data:
            rows = []
            for day in daily_data:
                for entry in day.get("entries", []):
                    rows.append({
                        "λ‚ μ§œ": day.get("task_date", ""),
                        "ν”Œλž«νΌ": entry.get("platform", ""),
                        "인용 횟수": entry.get("citation_count", 0),
                    })
            if rows:
                df = pd.DataFrame(rows)
                st.dataframe(df, use_container_width=True, hide_index=True)
        else:
            st.info("ν™ˆνŽ˜μ΄μ§€ 인용 데이터 μ—†μŒ")


@st.cache_data(ttl=300)
def get_report_feature_data(
    api_key: str,
    campaign_id: int,
    feature: str,
    start_date: str | None = None,
    end_date: str | None = None,
    access_token: str = "",
):
    """Fetch report feature data with caching."""
    client = ChainShiftClient(api_key=api_key or None, access_token=access_token or None)

    if feature == "overview":
        return client.get_report_overview(campaign_id, start_date, end_date)
    elif feature == "visibility":
        return client.get_report_visibility(campaign_id, start_date, end_date)
    elif feature == "citations":
        return client.get_report_citations(campaign_id, start_date, end_date, limit=50)
    elif feature == "citation-trends":
        return client.get_report_citation_trends(campaign_id, start_date, end_date)
    elif feature == "content-types":
        return client.get_report_content_types(campaign_id, start_date, end_date)
    elif feature == "sentiment":
        return client.get_report_sentiment(campaign_id)
    elif feature == "homepage-citations":
        return client.get_report_homepage_citations(campaign_id, start_date, end_date)
    else:
        return {"success": False, "error": f"Unknown feature: {feature}"}


def convert_report_data_to_csv(feature: str, data: dict) -> str:
    """Convert report feature data to CSV format."""
    output = io.StringIO()
    writer = csv.writer(output)

    if feature == "overview":
        dr = data.get("date_range", {})
        writer.writerow(["ν•­λͺ©", "κ°’"])
        writer.writerow(["캠페인 ID", data.get("campaign_id", "")])
        writer.writerow(["뢄석 κΈ°κ°„", f"{dr.get('start', '')} ~ {dr.get('end', '')}"])
        writer.writerow(["총 질문 수", data.get("total_tasks", 0)])
        writer.writerow(["총 λ‹΅λ³€ 수", data.get("total_answers", 0)])
        writer.writerow(["κ°€μ‹œμ„± λΉ„μœ¨ (%)", data.get("overall_visibility_pct", 0)])

    elif feature == "visibility":
        writer.writerow(["ν”Œλž«νΌ", "λΈŒλžœλ“œ", "μœ ν˜•", "κ°€μ‹œμ„± (%)", "λΈŒλžœλ“œ μ–ΈκΈ‰ 수", "총 λ‹΅λ³€ 수"])
        for platform in data.get("platforms", []):
            for brand in platform.get("brands", []):
                writer.writerow([
                    platform.get("platform", ""),
                    brand.get("brand_name", ""),
                    brand.get("brand_type", ""),
                    brand.get("visibility_pct", 0),
                    brand.get("brand_mentions", 0),
                    platform.get("total_answers", 0),
                ])

    elif feature == "citations":
        writer.writerow(["도메인", "μœ ν˜•", "인용 횟수", "λ‹΅λ³€ μ–ΈκΈ‰ 수", "λΉ„μœ¨ (%)"])
        for item in data.get("sources", []):
            writer.writerow([
                item.get("source_host_url", ""),
                item.get("source_host_type", ""),
                item.get("total_citations", 0),
                item.get("total_answer_mentions", 0),
                item.get("pct_of_total", 0),
            ])

    elif feature == "citation-trends":
        writer.writerow(["인용 좜처", "μœ ν˜•", "λ‚ μ§œ", "인용 횟수", "λ‹΅λ³€ μ–ΈκΈ‰ 수", "λΉ„μœ¨ (%)"])
        for source in data.get("sources", []):
            host = source.get("source_host_url", "")
            host_type = source.get("source_host_type", "")
            for point in source.get("trend", []):
                writer.writerow([
                    host,
                    host_type,
                    point.get("task_date", ""),
                    point.get("citation_count", 0),
                    point.get("answer_mention_count", 0),
                    point.get("citation_pct", 0),
                ])

    elif feature == "content-types":
        writer.writerow(["μ½˜ν…μΈ  μœ ν˜•", "인용 횟수", "λ‹΅λ³€ μ–ΈκΈ‰ 수", "λΉ„μœ¨ (%)"])
        for item in data.get("content_types", []):
            writer.writerow([
                item.get("content_type", ""),
                item.get("total_citations", 0),
                item.get("total_answer_mentions", 0),
                item.get("pct_of_total", 0),
            ])

    elif feature == "sentiment":
        writer.writerow(["λΈŒλžœλ“œ", "μœ ν˜•", "총 λ©˜μ…˜", "긍정 %", "λΆ€μ • %", "쀑립 %"])

        for item in data.get("in_house_brands", []):
            t = item.get("total_mentions", 0)
            neutral = round(item.get("neutral_count", 0) / t * 100, 1) if t > 0 else 0.0
            writer.writerow([
                item.get("brand_name", ""),
                "μžμ‚¬",
                t,
                f"{item.get('positive_rate', 0):.1f}",
                f"{item.get('negative_rate', 0):.1f}",
                f"{neutral:.1f}",
            ])

        for item in data.get("competitor_brands", []):
            t = item.get("total_mentions", 0)
            neutral = round(item.get("neutral_count", 0) / t * 100, 1) if t > 0 else 0.0
            writer.writerow([
                item.get("brand_name", ""),
                "κ²½μŸμ‚¬",
                item.get("total_mentions", 0),
                f"{item.get('positive_rate', 0):.1f}",
                f"{item.get('negative_rate', 0):.1f}",
                f"{neutral:.1f}",
            ])

        if not data.get("in_house_brands") and not data.get("competitor_brands"):
            for item in data.get("brands", []):
                pos = item.get("positive_rate", item.get("positive", 0))
                neg = item.get("negative_rate", item.get("negative", 0))
                neutral = 100 - pos - neg
                writer.writerow([
                    item.get("brand_name", item.get("name", "")),
                    item.get("brand_type", item.get("type", "")),
                    item.get("total_mentions", 0),
                    f"{pos:.1f}",
                    f"{neg:.1f}",
                    f"{neutral:.1f}",
                ])

    elif feature == "homepage-citations":
        writer.writerow(["λ‚ μ§œ", "ν”Œλž«νΌ", "인용 좜처", "인용 횟수", "λ‹΅λ³€ μ–ΈκΈ‰ 수"])
        for day in data.get("daily_data", []):
            task_date = day.get("task_date", "")
            for entry in day.get("entries", []):
                writer.writerow([
                    task_date,
                    entry.get("platform", ""),
                    entry.get("source_host_url", ""),
                    entry.get("citation_count", 0),
                    entry.get("answer_mention_count", 0),
                ])

    return output.getvalue()