
    w5i+                    D   d Z ddlmZ ddlZddlZddlmZ ddlZddlm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  ej2                          ej4                  d      d,d              Zej9                          ej:                  dddd ej                  d             ej:                  dddd       ej:                  dddd ej                                ej:                  ddd !       ej:                  d" ej                  d      d#$      	 	 	 	 	 	 	 	 	 	 	 	 d-d%                                          Zej9                          ej:                  dddd ej                  d            d.d&              Zej9                          ej:                  dddd ej                  d            d.d'              Z ej9                          ej:                  dddd( ej                               d/d)              Z!d,d*Z"e#d+k(  r e"        yy)0z$PlanitAI KPI - Main CLI entry point.    )annotationsN)Path)Config)GoogleSheetsClientMockSheetsClient)KPITree)KPICalculator)KPIAnalyzer)GeminiClient)
AIAnalyzer)HTMLReportGeneratorz0.1.0)versionc                      y)z,PlanitAI KPI - AI-powered KPI analysis tool.N r       ]/var/www/tkim.planitai.co.jp/gemegg/20251207-make-pdf-report/project/planitai-kpi/src/main.pyclir      s     	r   z--configz-czconfig.yamlzPath to configuration file.T)exists)defaulthelptypez--periodz-pu4   Analysis period (e.g., '2024-11' or '2024年11月').)requiredr   z--outputz-oz./outputzOutput directory for reports.z	--skip-aiz'Skip AI analysis (faster, for testing).)is_flagr   z--mock-dataz6Use mock data from JSON file instead of Google Sheets.)r   r   c           
        t        j                  d       t        j                  d       t        j                  d       	 t        j                  |       }|j	                  |xs t        |            }|r6|D ]  }t        j                  d| d        t        j                  d       t        j                  d	       t        j                  d       	 |rgt        |      5 }	t        j                  |	      }
ddd       
j                  di       }|
j                  di       }t        j                  d|        nt        j                        }|j                  j                   j"                  r[|j                  j                   j$                  |j                  j                   j&                  |j                  j                   j(                  |j                  j                   j*                  |j                  j                   j,                  |j                  j                   j.                  |j                  j                   j0                  |j                  j                   j2                  |j                  j                   j4                  d	}|j7                  |j                  j8                  |j                  j:                  d|      \  }}nh|j7                  |j                  j8                  |j                  j:                  |j                  j<                  |j                  j>                        \  }}t        j                  dtA        |       d       ||vr\t        j                  d|        t        j                  dtC        |jE                                       t        j                  d       t        j                  d       	 tG        jH                  jJ                        }|jM                  |          |v r|jO                  ||          |j	                         }|r|D ]  }t        j                  d|         t        j                  dtA        |jP                         d       t        j                  d       	 tS              }|jU                         }t        j                  dtA        |       d       |jV                  }|jX                  V|jZ                  }|rd |d!d"nd}t        j                  d#|j\                   d$|jX                  d%d&|j^                   |        i }|st        j                  d(       	 j`                  st        j                  d)       ntc        |j`                        }te        |      }t        j                  d*       |jg                  |      |d+<   t        j                  d,       |ji                         |d-<   t        j                  d.       |jk                  |      |d/<   t        j                  d0       nt        j                  d3       t        j                  d4       	 tm               }|jo                  |||d5| 6      }t        j                  d7|        t        j                  d       t        j                  d9       t        j                  d: d;       y# t        $ r:}t        j                  d
| d       t        j                  d       Y d}~Nd}~ww xY w# 1 sw Y   xY w# t        $ r:}t        j                  d| d       t        j                  d       Y d}~d}~ww xY w# t        $ r:}t        j                  d| d       t        j                  d       Y d}~/d}~ww xY w# t        $ r:}t        j                  d'| d       t        j                  d       Y d}~d}~ww xY w# t        $ r8}t        j                  d1|        t        j                  d2       Y d}~d}~ww xY w# t        $ r:}t        j                  d8| d       t        j                  d       Y d}~d}~ww xY w)<z%Run KPI analysis and generate report.u   🚀 PlanitAI KPI Starting... u   📁 Loading configuration...)skip_aiu     ❌ Terr   u     ✅ Configuration loadedu     ❌ Failed to load config: Nu   📊 Fetching KPI data...actualtargetu     ✅ Loaded mock data from )	
period_row
header_rowdata_start_rowitem_coldata_start_colcols_per_periodbudget_col_offsetactual_col_offsetitem_mapping)sheet_id
data_rangepivot_formatpivot_config)r+   r,   target_rangeperiod_columnu     ✅ Fetched data for z periodsu#     ⚠️ No data found for period: z  Available periods: u     ❌ Failed to fetch data: u   🌳 Building KPI tree...u	     ⚠️ u     ✅ Tree built with z nodesu     ❌ Failed to build tree: u   🔢 Calculating KPIs...u     ✅ Calculated z KPIsz (z.1fz%)u     📈 z: z,.0f u     ❌ Failed to calculate: u   🤖 Running AI analysis...u)     ⚠️ No API key, skipping AI analysisu     ⏳ Analyzing trends...trendsu     ⏳ Analyzing bottlenecks...bottlenecksu%     ⏳ Generating executive summary...executive_summaryu     ✅ AI analysis completeu     ⚠️ AI analysis failed: z#  Continuing without AI insights...u'   ⏭️ Skipping AI analysis (--skip-ai)u   📝 Generating report...zKPI Report - )treeanalysis_resultsperiodoutput_pathtitleu     ✅ Report generated: u!     ❌ Failed to generate report: u   ✨ Analysis complete!z   Open z$ in your browser to view the report.)8clickechor   	from_yamlvalidateboolsysexit	Exceptionopenjsonloadgetr   credentials_pathsheetpivotenabledr"   r#   r$   r%   r&   r'   r(   r)   r*   get_kpi_datar+   r,   r/   r0   lenlistkeysr   from_configr5   
set_valuesset_targetsnodesr	   	calculaterootvalueachievement_ratenameunitgemini_api_keyr   r   analyze_trendsanalyze_bottlenecksgenerate_executive_summaryr   generate)configr7   outputr   	mock_datacfgerrorserrorefdataactual_datatarget_datasheets_clientr.   r5   validation_errors
calculatorresultskgiachievementachievement_strr6   gemini_clientai_analyzer	generatorr8   s                              r   analyzerr      s   H 
JJ./	JJrN 
JJ./
v&g&@iA 7

VE7+67HHQK

/0 
JJ*+/i $Ayy|$((8R0K((8R0KJJ5i[AB /s/C/CDM yy&&"%))//"<"<"%))//"<"<&)iioo&D&D #		 8 8&)iioo&D&D'*yy'F'F),)J)J),)J)J$'IIOO$@$@
  ,9+E+E YY//"yy33!%!-	 ,F ,([ ,9+E+E YY//"yy33!$!7!7"%))"9"9	 ,F ,([ JJ0[1A0B(KL$JJ<VHEFJJ.tK4D4D4F/G.HIJHHQK 
JJ*+""388,F+,[ [01 MMO* 0

Yug./0 	

+C

O+<FCD 
JJ)*"4(
&&(

&s7|nE:; ii99 ..K:E;s"3262OJJ
"SYYt,<AchhZGXYZ 

01	>%%

FG ,S-?-? @(=

67-8-G-G-O *

;<2=2Q2Q2S /

BC8C8^8^_e8f !45

78 	

<= 
JJ*+')	((-!&* ) 
 	

-k];< 
JJrN	JJ'(	JJ+&JKLW  

21#6DA$ $T  

1!54@&  

1!54@$  

04$?4  	>JJ6qc:;JJ<==	>&  

6qc:Es   B[ \% %\;K\% B(]+ B+^1 C_7 ;`; 	\/\\\"\% %	](./]##](+	^.4/^))^.1	_4:/_//_47	`8 -`33`8;	a>/a99a>c                ~   t        j                  d       	 t        j                  |       }|j	                         }|rJt        j                  d       |D ]  }t        j                  d|         t        j                  d       yt        j                  d       t        j                  dt        |j                         d       t        j                  d|j                  j                  dd	  d
       y# t        $ r9}t        j                  d| d       t        j                  d       Y d}~yd}~ww xY w)zValidate configuration file.u    🔍 Validating configuration...u   ❌ Validation failed:z   - r   u   ✅ Configuration is valid!z KPI nodes definedz   - Sheet ID: N   z...u   ❌ Failed to load config: Tr   )r:   r;   r   r<   r=   r?   r@   rK   r5   rG   r+   rA   )r]   r`   ra   rb   rc   s        r   r=   r=      s     
JJ12v&JJ/0 ,

U5'?+,HHQKJJ45JJs388}o-?@AJJ););CR)@(AEF 

04$?s   A0C: A1C: :	D</D77D<c                   	 t        j                  |       }t        j                  |j                        }t        j                  d       t        j                  d       t        j                  |j                                y# t        $ r9}t        j                  d| d       t        j                  d       Y d}~yd}~ww xY w)zDisplay KPI tree structure.u   🌳 KPI Tree Structure:r   u   ❌ Failed: Tr   r   N)r   r<   r   rN   r5   r:   r;   to_textrA   r?   r@   )r]   r`   kpi_treerc   s       r   r5   r5      s    
v&&&sxx0

-.

2

8##%& 

\!%40s   BB 	C/CCzOutput file path.c                   d}t        |       }|j                         r/t        j                  d|  d      st        j                  d       yt        |dd      5 }|j                  |       ddd       t        j                  d	|         t        j                  d
       t        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  d
       t        j                  d       y# 1 sw Y   xY w)z"Create example configuration file.u  # PlanitAI KPI Configuration

# Google Sheets Settings
sheet:
  sheet_id: "YOUR_SHEET_ID_HERE"
  data_range: "Sheet1!A1:Z100"
  target_range: "Targets!A1:Z100"  # Optional
  period_column: "period"

# Gemini API Key (use environment variable)
gemini_api_key: "${GEMINI_API_KEY}"

# Output Settings
output_path: "./output"
language: "ja"

# Credentials file for Google Sheets
credentials_path: "credentials.json"

# KPI Tree Definition
tree:
  # KGI (Key Goal Indicator) - Top level
  - id: revenue
    name: 月間売上
    type: kgi
    formula: "{contracts} * {avg_price}"
    unit: 円
    category: finance
    children: [contracts, avg_price]

  # KPI (Key Performance Indicator) - Calculated metrics
  - id: contracts
    name: 契約数
    type: kpi
    formula: "{meetings} * {close_rate}"
    unit: 件
    category: sales
    children: [meetings, close_rate]

  - id: meetings
    name: 商談数
    type: kpi
    formula: "{leads} * {meeting_rate}"
    unit: 件
    category: sales
    children: [leads, meeting_rate]

  # INPUT - Leaf nodes (manually entered values)
  - id: avg_price
    name: 平均単価
    type: input
    unit: 円
    category: finance

  - id: close_rate
    name: 成約率
    type: input
    unit: "%"
    category: sales

  - id: leads
    name: リード数
    type: input
    unit: 件
    category: marketing

  - id: meeting_rate
    name: 商談化率
    type: input
    unit: "%"
    category: marketing
'z' already exists. Overwrite?z
Cancelled.Nwzutf-8)encodingu#   ✅ Created example configuration: r   zNext steps:z1  1. Update 'sheet_id' with your Google Sheets IDz,  2. Set GEMINI_API_KEY environment variablez;  3. Place your 'credentials.json' (Google service account)z-  4. Customize the KPI tree for your businessz+Then run: planitai-kpi analyze -p '2024-11')r   r   r:   confirmr;   rB   write)r^   example_configpathrd   s       r   initr     s    GNR <D{{}}}q(DEFJJ|$	dC'	*  a	  
JJ4VH=>	JJrN	JJ}	JJBC	JJ=>	JJLM	JJ>?	JJrN	JJ<=   s   D66D?c                     t                y)zMain entry point.N)r   r   r   r   mainr   u  s    Er   __main__)returnNone)r]   strr7   r   r^   r   r   r>   r_   z
str | Noner   r   )r]   r   r   r   )r^   r   r   r   )$__doc__
__future__r   rC   r?   pathlibr   r:   
src.configr   src.sheets.clientr   r   src.kpi.treer   src.kpi.calculatorr	   src.kpi.analyzerr
   src.ai.clientr   src.ai.analyzerr   src.output.htmlr   groupversion_optionr   commandoptionrr   r=   r5   r   r   __name__r   r   r   <module>r      sl   * "  
    B   , ( & & / g&	 ' 	
 	&	4	 	 	?
 	(		 	2
 	4	 	A
`M`M`M `M 	`M
 `M 
`M 8`MF 	&	4	 	 . 	&	4	 	  			\> \>~

 zF r   