"""
Showroom Simple Data Analysis Workflow
This module contains the simple data analysis workflow for 1-2 metrics with customizable parameters.
Suitable for periodic analysis with line charts and bar charts, intelligently generated by AI.
"""

# Integrated HTML template for Simple Data Analysis
SIMPLE_DATA_ANALYSIS_HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{REPORT_TITLE}} Analysis Report</title>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 40px;
            line-height: 1.6;
            background-color: #f8f9fa;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #1e3a8a;
            border-bottom: 3px solid #3b82f6;
            padding-bottom: 15px;
            margin-bottom: 30px;
            font-size: 2.2em;
        }}
        h2 {{
            color: #1e40af;
            margin-top: 35px;
            margin-bottom: 20px;
            font-size: 1.5em;
        }}
        .summary-box {{
            background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
            padding: 25px;
            border-radius: 8px;
            margin: 25px 0;
            border-left: 5px solid #3b82f6;
        }}
        .metrics-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin: 25px 0;
        }}
        .metric-card {{
            background-color: #f8fafc;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            text-align: center;
        }}
        .metric-value {{
            font-size: 2em;
            font-weight: bold;
            color: #1e40af;
            margin: 10px 0;
        }}
        .metric-label {{
            color: #64748b;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 1px;
        }}
        table {{
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
            background-color: white;
        }}
        th, td {{
            border: 1px solid #e2e8f0;
            padding: 12px;
            text-align: left;
        }}
        th {{
            background-color: #1e40af;
            color: white;
            font-weight: 600;
        }}
        tr:nth-child(even) {{
            background-color: #f8fafc;
        }}
        .chart-container {{
            margin: 30px 0;
            text-align: center;
        }}
        .chart-container img {{
            max-width: 100%;
            height: auto;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }}
        .insight-box {{
            background-color: #fef3c7;
            border-left: 5px solid #f59e0b;
            padding: 20px;
            margin: 25px 0;
            border-radius: 0 8px 8px 0;
        }}
        .footer {{
            margin-top: 50px;
            padding-top: 25px;
            border-top: 2px solid #e2e8f0;
            color: #64748b;
            font-size: 0.9em;
            text-align: center;
        }}
        .trend-indicator {{
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            font-weight: bold;
        }}
        .trend-up {{
            background-color: #dcfce7;
            color: #166534;
        }}
        .trend-down {{
            background-color: #fecaca;
            color: #991b1b;
        }}
        .trend-neutral {{
            background-color: #f1f5f9;
            color: #475569;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>📊 {{REPORT_TITLE}} Analysis Report</h1>
        
        <div class="summary-box">
            <h2>📊 Analysis Overview</h2>
            <p><strong>Analysis date:</strong> {{ANALYSIS_DATE}}</p>
            <p><strong>Data source:</strong> {{DATA_SOURCE}}</p>
            <p><strong>Analysis period:</strong> {{ANALYSIS_PERIOD}}</p>
            <p><strong>Total records:</strong> {{TOTAL_RECORDS}}</p>
            <p><strong>Status:</strong> ✅ AI analysis complete</p>
        </div>
        
        <h2>🎯 Core Metrics</h2>
        <div class="metrics-grid">
            {{CORE_METRICS_CARDS}}
        </div>

        <h2>📈 Trend Charts</h2>
        <div class="chart-container">
            <h3>{{CHART_1_TITLE}}</h3>
            <img src="{{CHART_1_PATH}}" alt="{{CHART_1_ALT}}">
        </div>
        
        <div class="chart-container">
            <h3>{{CHART_2_TITLE}}</h3>
            <img src="{{CHART_2_PATH}}" alt="{{CHART_2_ALT}}">
        </div>

        <h2>📋 Detailed Data Table</h2>
        <table>
            <thead>
                <tr>
                    {{TABLE_HEADERS}}
                </tr>
            </thead>
            <tbody>
                {{TABLE_ROWS}}
            </tbody>
        </table>

        <div class="insight-box">
            <h2>💡 AI Insights</h2>
            <ul>
                {{AI_INSIGHTS}}
            </ul>
        </div>

        <h2>📊 Data Overview</h2>
        <div class="summary-box">
            <p><strong>Data fields:</strong> {{DATA_FIELDS}}</p>
            <p><strong>AI analysis summary:</strong> {{AI_ANALYSIS_SUMMARY}}</p>
        </div>
        
        <div class="footer">
            <p>📊 Report generated by PM Studio MCP - Showroom Simple Data Analysis</p>
            <p>🤖 AI-driven analysis, no Python scripting required; supports dynamic charts</p>
            <p>🔍 For deeper analysis, contact the PM Studio team</p>
            <p>⏰ Generated at: {{GENERATION_TIME}}</p>
        </div>
    </div>
</body>
</html>"""

SIMPLE_DATA_ANALYSIS_PARAMETER_REQUEST_TEMPLATE = """---
mode: 'agent'
---
# Missing Parameter: Metric Name

## Parameter Required
This workflow requires a specific metric to analyze.

**Example inputs:**
- "Edge Mobile DAU" — daily active users for Edge Mobile
- "Quark BSoM" — monthly active for Quark browser  
- "Chrome retention rate" — Chrome user retention
- "Doubao DAU" — daily active for Doubao

### How to restart:
```
get_showroom_guide("your_name", "showroom_simple_data_analysis", "METRIC_NAME")
```

**Please provide a metric name to continue.**
"""

SIMPLE_DATA_ANALYSIS_DYNAMIC_WORKFLOW_TEMPLATE = """---
mode: 'agent'
---
# Showroom Simple Data Analysis - Workflow

## 📊 Analysis Goal
User input: {{original_input}}
Product: {{product}}
Metric type: {{metric_type}}
Time range: {{time_range}}

## ⚠️ Important
⚠️ This workflow is designed for simple analysis of 1–2 metrics.
⚠️ Supports custom metrics and periods; AI will generate a professional HTML report with line and bar charts.

## ⛔ Confirm before executing ⛔

Before starting, ask the user:

"Task Plan - Simple Data Analysis for: {{original_input}}

1. Environment setup + isolated workspace creation
2. Search Titan templates for {{product}} {{metric_type}}
3. Execute query and save CSV data
4. Generate line/bar charts using AI visualization
5. Create HTML report with integrated template

Expected outputs: CSV data + 2 charts + HTML report

Confirm to proceed? (yes/no)"

Wait for explicit confirmation before proceeding.

## Step-by-step

### Step 1: Environment and path checks & create isolated run directory
⚠️ Mandatory checks before any action ⚠️

```
Environment checks (must not be skipped):
1. Locate project root directory using AI reasoning:
   - Find the directory containing pyproject.toml, .venv, and working_dir
   - Navigate to that directory using run_in_terminal "cd [calculated_path]"
   - This should be the pm-studio-mcp project root directory
2. Verify project root location: run_in_terminal "dir pyproject.toml .venv working_dir"
3. Generate timestamp via AI reasoning (format: YYYYMMDD_HHMMSS)
4. Create isolated workspace using exact mkdir command:
   run_in_terminal "mkdir working_dir\<timestamp>_simple_data_analysis"
5. Set RUN_DIR = working_dir\<timestamp>_simple_data_analysis

Virtual environment requirements:
- All Python execution must use .venv\Scripts\python.exe
- Never use plain "python" command
- Print full venv Python path before execution

Path discipline:
- All files read/write within RUN_DIR only
- Output filenames start with timestamp prefix
- No hardcoded absolute paths
```

### Step 2: Smart data query
Select data source based on your metric:

```
1. Search templates: titan_search_table_metadata_tool with "{{search_key}}"
2. Generate SQL: titan_generate_sql_from_template_tool with filters:
   - Metric type: {{metric_type}}
   - Time range: {{time_range}}
   - Product: {{product}}
3. Execute query: titan_query_data_tool
4. Save CSV to RUN_DIR: <timestamp>_simple_data_analysis_raw.csv

NEVER re-execute queries. Check results once with dir command.
```

### Step 3: AI analysis and HTML report generation
Proceed only after environment checks.
Do not write Python; use the integrated HTML template only.

```
Environment verification:
- Verify .venv\Scripts\python.exe path
- Confirm working_dir accessible
- All operations within RUN_DIR only

Analysis flow:
1. Verify CSV exists: run_in_terminal "dir RUN_DIR\*.csv"
2. Generate charts using generate_data_visualization:
   - Chart 1 (line): {{metric_type}} over time
   - Chart 2 (bar): comparison by time
   - Save charts to RUN_DIR with timestamp prefix
3. Create HTML report using integrated template:
   - Get template: get_simple_data_analysis_html_template()
   - Replace placeholders: REPORT_TITLE, ANALYSIS_DATE, etc.
   - Save to RUN_DIR: <timestamp>_{{product}}_{{metric_type}}_simple_analysis_report.html

After generation, verify outputs:
run_in_terminal "dir RUN_DIR\*.html"

DO NOT re-execute. Report results to user.
```

### Key differentiators
- Tailored for 1–2 metrics
- Periodic analysis with custom time range
- Smart chart generation (line and bar)
- Professional, modern report template

## Completion Protocol
```
Final verification: run_in_terminal "dir RUN_DIR"

Success criteria:
- 1 CSV file from Titan query
- 2 chart files (PNG format)  
- 1 HTML report with timestamp prefix
- All files isolated in RUN_DIR

Report completion with file locations.
```

## Done
Notify the user: "The simple analysis report for '{{original_input}}' has been generated. A professional HTML report with line and bar charts is ready, and the filename includes the analyzed metric."
"""

def parse_metric_parameter(metric: str) -> dict:
    """
    Simple metric parameter parsing - let AI handle the intelligence
    """
    return {
        "original_input": metric,
        "search_key": metric,  # use user input directly as search keyword
        "metric_type": "auto",  # let AI determine the metric type
        "product": "auto",  # let AI determine the product
        "time_range": "last 30 days"  # default time range
    }

def generate_dynamic_workflow(config: dict) -> str:
    """
    Generate a dynamic workflow based on the parsed configuration
    
    Args:
        config: Analysis configuration
    """
    # Use fixed basic template
    template_file = "showroom_report_template.html"
    
    # Append template info into the workflow content
    workflow = SIMPLE_DATA_ANALYSIS_DYNAMIC_WORKFLOW_TEMPLATE.format(
        original_input=config["original_input"],
        search_key=config["search_key"],
        metric_type=config["metric_type"],
        product=config["product"],
        time_range=config["time_range"]
    )
    
    # Add template selection notes in step 2
    workflow += f"""

## Template Configuration
Uses integrated HTML template (Blue business theme).

Requirements:
- Use get_simple_data_analysis_html_template() for template
- Replace only placeholder variables
- No custom Python code generation
- Output: RUN_DIR/<timestamp>_{{product}}_{{metric_type}}_simple_analysis_report.html
- Virtual env: .venv\Scripts\python.exe for any Python needs
"""
    
    return workflow

def get_simple_data_analysis_html_template():
    """
    Get the integrated HTML template for simple data analysis reports
    """
    return SIMPLE_DATA_ANALYSIS_HTML_TEMPLATE

def get_showroom_simple_data_analysis_workflow(metric_parameter: str = None, template_name: str = "basic") -> str:
    """
    Simple Data Analysis Workflow
    
    Args:
        metric_parameter: The metric to analyze (user-provided)
        template_name: Template name (deprecated, only "basic" is supported)
    """
    
    # 1. Ask for metric if not provided
    if not metric_parameter:
        return SIMPLE_DATA_ANALYSIS_PARAMETER_REQUEST_TEMPLATE
    
    # 2. Generate the dynamic workflow (ignore template_name)
    analysis_config = parse_metric_parameter(metric_parameter)
    return generate_dynamic_workflow(analysis_config)
