o
    ?5i#                     @   sb   d Z ddlmZ ddlmZ ddlmZ ddlZddlmZm	Z	m
Z
 ddlmZ G d	d
 d
ZdS )z0HTML Report Generator - Full Money Forward Style    )Path)datetime)OptionalN   )FinancialReportPLItemKPICard)format_currencyc                   @   sV  e Zd ZdZ	d7dededefddZdefd	d
Zdd Z	de
de
fddZde
fddZde
fddZde
fddZde
fddZdede
de
fddZde
fddZde
fddZde
fd d!Zde
fd"d#Zde
fd$d%Zde
fd&d'Zde
fd(d)Zde
fd*d+Zde
fd,d-Zde
fd.d/Zde
fd0d1Zde
fd2d3Zde
fd4d5Zd6S )8HTMLReportGeneratorzBHTML Report Generator with Chart.js, Google Fonts, and AI AnalysisToutput_pathreport_datause_aic                 C   s,   t || _|| _|| _d | _d | _d | _d S N)r   r   datar   
ai_summaryai_varianceai_highlights)selfr   r   r    r   Z/var/www/tkim.planitai.co.jp/gemegg/20251207-make-pdf-report/project/src/html/generator.py__init__   s   

zHTMLReportGenerator.__init__returnc                 C   s>   | j r|   |  }| jjjddd | jj|dd | jS )zGenerate HTML reportT)parentsexist_okzutf-8)encoding)r   _generate_ai_content_build_htmlr   parentmkdir
write_text)r   Zhtml_contentr   r   r   generate   s   zHTMLReportGenerator.generatec              
   C   s   z3ddl m} | }td | || j| _td | || j| _td |	| j| _
W dS  tyV } ztd|  d| _d| _d| _
W Y d}~dS d}~ww )zGenerate AI-powered contentr   )get_gemini_clientz    Generating AI summary...z&    Generating AI variance analysis...z)    Generating AI financial highlights...z    AI generation failed: N)Z	ai_clientr!   print_clean_ai_responseZgenerate_financial_summaryr   r   Zgenerate_variance_analysisr   Zgenerate_financial_highlightsr   	Exception)r   r!   clienter   r   r   r   (   s(   

z(HTMLReportGenerator._generate_ai_contentresponsec                 C   s4   |s|S ddl }|dd|}|dd|}| S )z2Clean AI response by removing markdown code blocksr   Nz
```html\s* z```\s*)resubstrip)r   r'   r)   cleanedr   r   r   r#   A   s   z&HTMLReportGenerator._clean_ai_responsec                 C   s~   d| j j d| j j d|   d|   d|   d|   d|   d|   d	| 	  d
| 
  d|   d|   dS )zBuild complete HTML documentz<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>z - a   Financial Report</title>

    <!-- Google Fonts - Noto Sans JP -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@300;400;500;700&display=swap" rel="stylesheet">

    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        zA
    </style>
</head>
<body>
    <div class="container">
        u  

        <!-- Navigation -->
        <nav class="nav-tabs">
            <a href="#dashboard" class="nav-tab active">業績見通し</a>
            <a href="#summary" class="nav-tab">サマリ</a>
            <a href="#pl-table" class="nav-tab">損益計算書</a>
            <a href="#analysis" class="nav-tab">業績分析表</a>
            <a href="#highlights" class="nav-tab">財務ハイライト</a>
        </nav>

        <!-- Page 1: Dashboard -->
        <section id="dashboard" class="page">
            z}
        </section>

        <!-- Page 2: Summary (AI Generated) -->
        <section id="summary" class="page">
            zq
        </section>

        <!-- Page 3: P/L Table -->
        <section id="pl-table" class="page">
            z|
        </section>

        <!-- Page 4: Performance Analysis -->
        <section id="analysis" class="page">
            z~
        </section>

        <!-- Page 5: Financial Highlights -->
        <section id="highlights" class="page">
            z
        </section>

        z"
    </div>

    <script>
        z	
        z
    </script>
</body>
</html>)r   company_namefiscal_year_get_styles_build_header_build_dashboard_page_build_summary_page_build_pl_table_page_build_analysis_page_build_highlights_page_build_footer_build_chart_scripts_build_nav_scriptsr   r   r   r   r   L   s2   "',169=>zHTMLReportGenerator._build_htmlc                 C      dS )z
CSS stylesu#  
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans JP', sans-serif;
            background-color: #f8fafc;
            color: #334155;
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        /* Header */
        .header {
            background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
            color: white;
            padding: 40px;
            border-radius: 16px;
            margin-bottom: 24px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .header .subtitle {
            font-size: 16px;
            opacity: 0.9;
        }

        .header .period {
            font-size: 14px;
            opacity: 0.8;
            margin-top: 12px;
        }

        /* Navigation */
        .nav-tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 24px;
            background: white;
            padding: 8px;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            flex-wrap: wrap;
        }

        .nav-tab {
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            color: #64748b;
            font-weight: 500;
            transition: all 0.2s;
        }

        .nav-tab:hover {
            background: #f1f5f9;
            color: #334155;
        }

        .nav-tab.active {
            background: #2563eb;
            color: white;
        }

        /* Page sections */
        .page {
            display: none;
        }

        .page.active {
            display: block;
        }

        /* Section */
        .section {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 24px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .section-title {
            font-size: 20px;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 24px;
            padding-bottom: 12px;
            border-bottom: 2px solid #e2e8f0;
        }

        .section-subtitle {
            font-size: 16px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 16px;
        }

        /* Two column layout */
        .two-columns {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }

        /* KPI Cards */
        .kpi-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 16px;
        }

        .kpi-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            border-left: 4px solid;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .kpi-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .kpi-card.blue { border-left-color: #2563eb; }
        .kpi-card.green { border-left-color: #16a34a; }
        .kpi-card.red { border-left-color: #dc2626; }
        .kpi-card.purple { border-left-color: #8b5cf6; }
        .kpi-card.cyan { border-left-color: #0891b2; }
        .kpi-card.orange { border-left-color: #f59e0b; }

        .kpi-label {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 4px;
        }

        .kpi-title {
            font-size: 13px;
            color: #64748b;
            margin-bottom: 8px;
        }

        .kpi-value {
            font-size: 24px;
            font-weight: 700;
            color: #1e293b;
        }

        .kpi-value.negative {
            color: #dc2626;
        }

        .kpi-variance {
            font-size: 13px;
            margin-top: 8px;
            padding: 4px 8px;
            border-radius: 4px;
            display: inline-block;
        }

        .kpi-variance.positive {
            background: #dcfce7;
            color: #16a34a;
        }

        .kpi-variance.negative {
            background: #fee2e2;
            color: #dc2626;
        }

        .kpi-target {
            font-size: 11px;
            color: #94a3b8;
            margin-top: 4px;
        }

        /* Charts */
        .chart-container {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;
        }

        .chart-title {
            font-size: 14px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 16px;
            text-align: center;
        }

        /* Tables */
        .table-wrapper {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }

        th, td {
            padding: 10px 12px;
            text-align: right;
            border-bottom: 1px solid #e2e8f0;
        }

        th {
            background: #2563eb;
            color: white;
            font-weight: 500;
            position: sticky;
            top: 0;
        }

        th:first-child, td:first-child {
            text-align: left;
            position: sticky;
            left: 0;
            background: inherit;
            z-index: 1;
        }

        tr:nth-child(even) {
            background: #f8fafc;
        }

        tr:hover {
            background: #f1f5f9;
        }

        tr.total-row {
            background: #dbeafe !important;
            font-weight: 600;
        }

        tr.sub-item td:first-child {
            padding-left: 24px;
            color: #64748b;
            font-size: 12px;
        }

        .negative { color: #dc2626; }
        .positive { color: #16a34a; }

        /* AI Summary Box */
        .ai-summary {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-radius: 12px;
            padding: 24px;
            border-left: 4px solid #0891b2;
        }

        .ai-summary h3 {
            color: #0891b2;
            font-size: 16px;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .ai-summary ul {
            list-style: none;
            padding: 0;
        }

        .ai-summary li {
            padding: 8px 0;
            padding-left: 20px;
            position: relative;
            line-height: 1.6;
        }

        .ai-summary li:before {
            content: "•";
            position: absolute;
            left: 0;
            color: #0891b2;
            font-weight: bold;
        }

        /* Radar Chart Container */
        .radar-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 40px;
            flex-wrap: wrap;
        }

        .radar-chart-wrapper {
            width: 400px;
            height: 400px;
        }

        /* Score Cards */
        .score-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
        }

        .score-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 16px;
            text-align: center;
        }

        .score-card .label {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 8px;
        }

        .score-card .score {
            font-size: 28px;
            font-weight: 700;
            color: #2563eb;
        }

        .score-card .max {
            font-size: 14px;
            color: #94a3b8;
        }

        .grade-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2563eb, #1d4ed8);
            color: white;
            font-size: 36px;
            font-weight: 700;
            margin-bottom: 16px;
        }

        /* Footer */
        .footer {
            text-align: center;
            padding: 20px;
            color: #64748b;
            font-size: 13px;
        }

        /* Print styles */
        @media print {
            body { background: white; }
            .container { max-width: 100%; padding: 0; }
            .nav-tabs { display: none; }
            .page { display: block !important; page-break-after: always; }
            .section { box-shadow: none; border: 1px solid #e2e8f0; }
            .header { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }

        @media (max-width: 768px) {
            .two-columns { grid-template-columns: 1fr; }
            .score-grid { grid-template-columns: repeat(2, 1fr); }
            .kpi-grid { grid-template-columns: repeat(2, 1fr); }
            .radar-container { flex-direction: column; }
        }
        r   r9   r   r   r   r/         zHTMLReportGenerator._get_stylesc              	   C   s.   d| j j d| j j d| j j d| j j d	S )zBuild header sectionut   
        <header class="header">
            <h1>業績見通し</h1>
            <div class="subtitle">組織名：u6   </div>
            <div class="period">会計期間：u   （u3   ）</div>
            <div class="period">対象：z!</div>
        </header>
        )r   r-   r.   periodtarget_monthr9   r   r   r   r0     s   z!HTMLReportGenerator._build_headerc                 C   sP   |  | jjdd d}|  | jjdd | jj}d| d| jj d| dS )u&   Build dashboard page (業績見通し)N   u   着地見込u  
        <div class="section">
            <h2 class="section-title">業績見通し</h2>
            <p style="text-align: right; color: #64748b; margin-bottom: 16px;">（単位：円）</p>

            <div class="two-columns">
                <div>
                    <h3 class="section-subtitle">年間着地見込</h3>
                    <div class="kpi-grid">
                        u  
                    </div>
                </div>
                <div>
                    <div class="chart-container">
                        <div class="chart-title">売上高・利益推移（年間）</div>
                        <canvas id="chart-annual" height="250"></canvas>
                    </div>
                </div>
            </div>

            <div style="margin-top: 32px;" class="two-columns">
                <div>
                    <h3 class="section-subtitle">uO   実績</h3>
                    <div class="kpi-grid">
                        u}  
                    </div>
                </div>
                <div>
                    <div class="chart-container">
                        <div class="chart-title">売上高・利益推移（月次）</div>
                        <canvas id="chart-monthly" height="250"></canvas>
                    </div>
                </div>
            </div>
        </div>
        )_build_kpi_sectionr   annual_kpisr=   )r   Zannual_kpis_htmlZmonthly_kpis_htmlr   r   r   r1     s   	z)HTMLReportGenerator._build_dashboard_pagekpislabelc                 C   s   ddddddd}d}|D ]`}| |jd}|jd	k }|rd
nd}d}	|jrT|jd	krT|j|j }
|
d	kr7dnd
}|
d	kr?dnd}dt|j d| d| t|
 d}	|d| d|j d| d|j d| d|	 d7 }q|S )zBuild KPI cards HTMLZblueZgreenZredZpurpleZcyanZorange)z#2563ebz#16a34az#dc2626z#8b5cf6z#0891b2z#f59e0br(   r   negativepositive+u1   
                <div class="kpi-target">予算: z0</div>
                <div class="kpi-variance ">z</div>
                z"
            <div class="kpi-card z*">
                <div class="kpi-title">z-</div>
                <div class="kpi-value z.</div>
                <div class="kpi-label"> 
            </div>
            )getcolorvaluetarget_valuer	   titleformatted_value)r   rA   rB   Z	color_mapZ
cards_htmlkpiZcolor_classZis_negativeZvalue_classZvariance_htmlvariance	var_classvar_signr   r   r   r?   R  sP   	
	z&HTMLReportGenerator._build_kpi_sectionc                 C   s8   d}| j rd| j  d}nd}|  }d| d| dS )z#Build summary page with AI analysisr(   uf   
            <div class="ai-summary">
                <h3>🤖 AI分析サマリ</h3>
                rG   u   
            <div class="ai-summary">
                <h3>📊 財務サマリ</h3>
                <p>AIサマリを生成するには、GOOGLE_API_KEYを設定してください。</p>
            </div>
            ua   
        <div class="section">
            <h2 class="section-title">サマリ</h2>

            u   

            <div style="margin-top: 24px;">
                <h3 class="section-subtitle">主要指標サマリ</h3>
                z+
            </div>
        </div>
        )r   _build_summary_table)r   Z
ai_contentZsummary_tabler   r   r   r2   x  s   
z'HTMLReportGenerator._build_summary_pagec           
      C   s   dd | j jD }|sdS d}|dd D ]U}|j}|j}|j}|j}|dkr)dnd	}|r3|d
kr3dn|r7d	nd}	|d|jr@dnd d|j dt| dt| d| dt| d|	 d|rd|ddnd d7 }qd| dS )zBuild summary tablec                    s0   g | ] t  fd ddD r jdkr qS )c                 3   s    | ]}| j v V  qd S r   name.0kwitemr   r   	<genexpr>  s    zFHTMLReportGenerator._build_summary_table.<locals>.<listcomp>.<genexpr>)	   売上高u   売上原価	   売上総   営業u   経常	   純利益r   )anylevel)rV   r   rX   r   
<listcomp>  s    
z<HTMLReportGenerator._build_summary_table.<locals>.<listcomp>"   <p>データがありません</p>r(   N
   r   rD   rC   d   z
            <tr class="	total-rowz">
                <td>z</td>
                <td>z!</td>
                <td class="rF   z.1f%-z$</td>
            </tr>
            u  
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>科目</th>
                        <th>予算（累計）</th>
                        <th>実績（累計）</th>
                        <th>差異</th>
                        <th>達成率</th>
                    </tr>
                </thead>
                <tbody>
                    zF
                </tbody>
            </table>
        </div>
        )	r   pl_itemstotal_budgettotal_actualtotal_variancetotal_achievement_rateis_totalrT   r	   )
r   Zsummary_items	rows_htmlrY   budgetactualrO   raterP   Z
rate_classr   r   r   rR     sB   
z(HTMLReportGenerator._build_summary_tablec                 C   s6  | j jsdS | j jdd }d}|D ]
}|d| d7 }q|d7 }d}| j jD ]j}d}|jr1d	}n|jd
kr8d}d|j d}t|D ]+\}}|t|jk rj|j| j	}	|	d
k rZdnd}
|d|
 dt
|	 d7 }qC|d7 }qC|jd
k rvdnd}|d| dt
|j d7 }|d| d| d7 }q'd| d| dS )zBuild P/L table pageu=   <div class="section"><p>データがありません</p></div>N   u   <th>科目</th>z<th>z</th>u   <th>合計</th>r(   re   r   zsub-itemz<td>z</td>rC   z<td class="rF   z
<td>-</td>z<tr class="z</tr>u9  
        <div class="section">
            <h2 class="section-title">損益計算書</h2>
            <p style="text-align: right; color: #64748b; margin-bottom: 16px;">（単位：円）</p>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>zW</tr>
                    </thead>
                    <tbody>
                        za
                    </tbody>
                </table>
            </div>
        </div>
        )r   rh   month_labelsrm   r`   rT   	enumeratelenmonthly_valuesrp   r	   rj   )r   rs   Zheader_htmlmonthrn   rY   Z	row_classcellsivalZ	val_classZtotal_classr   r   r   r3     s:   

z(HTMLReportGenerator._build_pl_table_pagec              	   C   sF   d}| j rd| j  d}|  }d| jj d| d| jj d| d	S )	u1   Build performance analysis page (業績分析表)r(   u   
            <div class="ai-summary" style="margin-bottom: 24px;">
                <h3>🤖 AI差異分析</h3>
                rG   u   
        <div class="section">
            <h2 class="section-title">業績分析表</h2>
            <p style="color: #64748b; margin-bottom: 24px;">対象：z</p>

            zo

            <div class="two-columns">
                <div>
                    <h3 class="section-subtitle">u!    実績</h3>
                    uW  
                </div>
                <div>
                    <div class="chart-container">
                        <div class="chart-title">予算 vs 実績比較</div>
                        <canvas id="chart-comparison" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>
        )r   _build_comparison_kpisr   r=   )r   Zai_analysisZcomparison_htmlr   r   r   r4      s   	
z(HTMLReportGenerator._build_analysis_pagec                    s   g d}d}| j jD ]Q t fdd|D r[ jr[ jr" jd nd}|r[|j|j }|dkr2dnd	}|dkr:d
nd}|d j dt|j dt|j d| d| t| d7 }q
|r`|S dS )zBuild comparison KPI cards)r[   r\   r]   r^   r(   c                 3   s$    | ]}| j v o jd kV  qdS r   NrT   r`   rU   rX   r   r   rZ   *  s   " z=HTMLReportGenerator._build_comparison_kpis.<locals>.<genexpr>Nr   rD   rC   rE   z
                        <div class="kpi-card blue" style="margin-bottom: 12px;">
                            <div class="kpi-title">z:</div>
                            <div class="kpi-value">uC   </div>
                            <div class="kpi-target">予算: z<</div>
                            <div class="kpi-variance rF   z></div>
                        </div>
                        rb   )r   rh   r_   rv   rp   ro   rT   r	   )r   Z	key_itemsZcardsZ
last_monthrO   rP   rQ   r   rX   r   r{   $  s2   
	z*HTMLReportGenerator._build_comparison_kpisc           	      C   s   | j r<| j dd}| j dd}| j di }| j dd}d}| D ]\}}|dd	}|d
| d| d7 }q%nd}d}d}d}d| jj d| d| d| d| dS )u7   Build financial highlights page (財務ハイライト)total_score   gradeBscoresZoverall_commentr(   score   zQ
                <div class="score-card">
                    <div class="label">z.</div>
                    <div class="score">zI<span class="max">/5</span></div>
                </div>
                uD   財務分析を行うにはAI機能を有効にしてください。u  
            <div class="score-card"><div class="label">売上持続性</div><div class="score">3<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">収益性</div><div class="score">4<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">生産性</div><div class="score">4<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">健全性</div><div class="score">4<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">効率性</div><div class="score">3<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">安全性</div><div class="score">3<span class="max">/5</span></div></div>
            u   
        <div class="section">
            <h2 class="section-title">財務ハイライト</h2>
            <p style="color: #64748b; margin-bottom: 24px;">対象：u   </p>

            <div class="radar-container">
                <div style="text-align: center;">
                    <h3 class="section-subtitle">総合評価</h3>
                    <div class="grade-badge">zK</div>
                    <div style="font-size: 24px; font-weight: 700;">z<span style="font-size: 16px; color: #64748b;">/30</span></div>
                    <p style="margin-top: 16px; color: #64748b; max-width: 300px;">uY  </p>
                </div>

                <div class="radar-chart-wrapper">
                    <canvas id="chart-radar"></canvas>
                </div>
            </div>

            <div style="margin-top: 32px;">
                <h3 class="section-subtitle">評価詳細</h3>
                <div class="score-grid">
                    zB
                </div>
            </div>
        </div>
        )r   rH   itemsr   r=   )	r   r   r   r   commentZscore_cardsrT   r   r   r   r   r   r5   =  s:   			
z*HTMLReportGenerator._build_highlights_pagec                 C   s    d| j jd d| j j dS )zBuild footerz;
        <footer class="footer">
            <p>Generated: z%Y-%m-%d %H:%Mz | z</p>
            <p style="margin-top: 8px; font-size: 12px;">Print this page (Ctrl+P / Cmd+P) to save as PDF</p>
            <p style="margin-top: 4px; font-size: 11px; color: #94a3b8;">Powered by Gemini AI</p>
        </footer>
        )r   generated_atstrftimer-   r9   r   r   r   r6   v  s
   z!HTMLReportGenerator._build_footerc                 C   sF   g }| |   | |   | |   | |   d|S )zBuild all Chart.js scripts
)append_build_annual_chart_build_monthly_chart_build_comparison_chart_build_radar_chartjoin)r   scriptsr   r   r   r7     s   
z(HTMLReportGenerator._build_chart_scriptsc                 C   s   t | jjdd }g }g }tdd | jjD d}tdd | jjD d}|r5dd |jdd D }|rCdd |jdd D }d	| d
t | dt | dS )zBuild annual combo chartNrr   c                 s       | ]
}|j d kr|V  qdS r[   NrS   rV   rY   r   r   r   rZ         z:HTMLReportGenerator._build_annual_chart.<locals>.<genexpr>c                 s   (    | ]}d |j v rd|j v r|V  qdS r]   u   損益NrS   r   r   r   r   rZ        & c                 S      g | ]}t |jqS r   floatrp   rV   vr   r   r   ra         z;HTMLReportGenerator._build_annual_chart.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   ra     r   z
        new Chart(document.getElementById('chart-annual'), {
            type: 'bar',
            data: {
                labels: ~   ,
                datasets: [
                    {
                        label: '売上高',
                        data: u-  ,
                        backgroundColor: '#93c5fd',
                        borderColor: '#2563eb',
                        borderWidth: 1,
                        yAxisID: 'y'
                    },
                    {
                        label: '営業利益',
                        data: u*  ,
                        type: 'line',
                        borderColor: '#dc2626',
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        tension: 0.1,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                interaction: { mode: 'index', intersect: false },
                scales: {
                    y: {
                        type: 'linear',
                        position: 'left',
                        ticks: { callback: v => (v/10000).toLocaleString() + '万' }
                    },
                    y1: {
                        type: 'linear',
                        position: 'right',
                        grid: { drawOnChartArea: false },
                        ticks: { callback: v => (v/10000).toLocaleString() + '万' }
                    }
                },
                plugins: { legend: { position: 'bottom' } }
            }
        });
        )jsondumpsr   rs   nextrh   rv   r   labelsZ
sales_dataZprofit_data
sales_itemprofit_itemr   r   r   r     s    z'HTMLReportGenerator._build_annual_chartc                 C   s   t t| jjdkr| jjdd n| jj}g }g }tdd | jjD d}tdd | jjD d}|rAdd |jdd D }|rOd	d |jdd D }d
| dt | dt | dS )zBuild monthly chartr>   iNc                 s   r   r   rS   r   r   r   r   rZ     r   z;HTMLReportGenerator._build_monthly_chart.<locals>.<genexpr>c                 s   r   r   rS   r   r   r   r   rZ     r   c                 S   r   r   r   r   r   r   r   ra     r   z<HTMLReportGenerator._build_monthly_chart.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   ra     r   z
        new Chart(document.getElementById('chart-monthly'), {
            type: 'bar',
            data: {
                labels: r   u   ,
                        backgroundColor: '#93c5fd'
                    },
                    {
                        label: '営業利益',
                        data: u  ,
                        backgroundColor: '#1e40af'
                    }
                ]
            },
            options: {
                responsive: true,
                scales: {
                    y: { ticks: { callback: v => (v/10000).toLocaleString() + '万' } }
                },
                plugins: { legend: { position: 'bottom' } }
            }
        });
        )r   r   ru   r   rs   r   rh   rv   r   r   r   r   r     s    .z(HTMLReportGenerator._build_monthly_chartc                    s   g d}g }g }|D ]- t  fdd| jjD d}|r-|t|j |t|j q
|d |d q
dt| dt| dt| d	S )
z'Build budget vs actual comparison chart)r[   u   売上総利益u   営業利益u   経常利益c                 3   s(    | ]} |j v r|jd kr|V  qdS r|   r}   )rV   ry   rB   r   r   rZ     r   z>HTMLReportGenerator._build_comparison_chart.<locals>.<genexpr>Nr   z
        new Chart(document.getElementById('chart-comparison'), {
            type: 'bar',
            data: {
                labels: u{   ,
                datasets: [
                    {
                        label: '予算',
                        data: u   ,
                        backgroundColor: '#cbd5e1'
                    },
                    {
                        label: '実績',
                        data: u  ,
                        backgroundColor: '#2563eb'
                    }
                ]
            },
            options: {
                responsive: true,
                scales: {
                    y: { ticks: { callback: v => (v/10000).toLocaleString() + '万' } }
                },
                plugins: { legend: { position: 'bottom' } }
            }
        });
        )	r   r   rh   r   r   ri   rj   r   r   )r   r   Zbudget_dataZactual_datarY   r   r   r   r     s"   
z+HTMLReportGenerator._build_comparison_chartc                    sp   | j rd| j v r| j d   fdddD }ng d}tg d}g d}d| dt| d	t| d
S )z*Build radar chart for financial highlightsr   c                    s    g | ]}  |i  d dqS )r   r   )rH   )rV   kr   r   r   ra   *  s     z:HTMLReportGenerator._build_radar_chart.<locals>.<listcomp>)u   売上持続性u	   収益性u	   生産性u	   健全性u	   効率性u	   安全性)r      r   r   r   r   )r   r   r   r   r   r   z
        new Chart(document.getElementById('chart-radar'), {
            type: 'radar',
            data: {
                labels: u{   ,
                datasets: [
                    {
                        label: '当社',
                        data: uO  ,
                        backgroundColor: 'rgba(37, 99, 235, 0.2)',
                        borderColor: '#2563eb',
                        borderWidth: 2,
                        pointBackgroundColor: '#2563eb'
                    },
                    {
                        label: '業種基準',
                        data: a  ,
                        backgroundColor: 'transparent',
                        borderColor: '#94a3b8',
                        borderWidth: 1,
                        borderDash: [5, 5],
                        pointBackgroundColor: '#94a3b8'
                    }
                ]
            },
            options: {
                responsive: true,
                scales: {
                    r: {
                        beginAtZero: true,
                        max: 5,
                        ticks: { stepSize: 1 }
                    }
                },
                plugins: { legend: { position: 'bottom' } }
            }
        });
        )r   r   r   )r   r   r   	benchmarkr   r   r   r   &  s   

z&HTMLReportGenerator._build_radar_chartc                 C   r:   )zBuild navigation scriptsaO  
        // Tab navigation
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.addEventListener('click', function(e) {
                e.preventDefault();

                // Remove active from all tabs
                document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));

                // Add active to clicked tab
                this.classList.add('active');

                // Show corresponding page
                const targetId = this.getAttribute('href').substring(1);
                document.getElementById(targetId).classList.add('active');
            });
        });

        // Show first page by default
        document.querySelector('.page').classList.add('active');
        r   r9   r   r   r   r8   Y  r;   z&HTMLReportGenerator._build_nav_scriptsN)T)__name__
__module____qualname____doc__r   r   boolr   r    r   strr#   r   r/   r0   r1   listr?   r2   rR   r3   r4   r{   r5   r6   r7   r   r   r   r   r8   r   r   r   r   r
      sD    
E   3&"24$9
>++3r
   )r   pathlibr   r   typingr   r   data_modelsr   r   r   Z
pdf.stylesr	   r
   r   r   r   r   <module>   s    