#!/usr/bin/env python3
import json
from pathlib import Path


def load_json(data_dir: Path, filename: str) -> dict:
    filepath = data_dir / filename
    if not filepath.exists():
        print(f"Warning: {filename} not found")
        return {}
    with open(filepath, "r") as f:
        return json.load(f)


def render_html(
    variables: dict, statistics: dict, sections: dict, graph: dict, charts: dict
) -> str:
    html_template = (
        """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Claude's Constitution Analysis System</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
    <header>
        <h1>Claude's Constitution Analysis System</h1>
        <div class="search-bar">
            <input type="text" id="search-input" placeholder="Search variables, sections, content...">
            <select id="search-filter">
                <option value="all">All</option>
                <option value="variables">Variables</option>
                <option value="sections">Sections</option>
            </select>
        </div>
    </header>

    <div class="container">
        <aside class="sidebar">
            <nav class="nav-menu">
                <button class="nav-btn active" data-tab="overview">Overview</button>
                <button class="nav-btn" data-tab="variables">Variables</button>
                <button class="nav-btn" data-tab="sections">Sections</button>
                <button class="nav-btn" data-tab="network">Network</button>
                <button class="nav-btn" data-tab="statistics">Statistics</button>
            </nav>
            
            <div class="filters">
                <h3>Filters</h3>
                <label><input type="checkbox" id="filter-core" checked> Core Values</label>
                <label><input type="checkbox" id="filter-hard" checked> Hard Constraints</label>
                <label><input type="checkbox" id="filter-soft" checked> Soft Factors</label>
                <div class="priority-filters">
                    <h4>Priority Levels</h4>
                    <label><input type="checkbox" class="filter-priority" value="1" checked> 1</label>
                    <label><input type="checkbox" class="filter-priority" value="2" checked> 2</label>
                    <label><input type="checkbox" class="filter-priority" value="3" checked> 3</label>
                    <label><input type="checkbox" class="filter-priority" value="4" checked> 4</label>
                </div>
            </div>
        </aside>

        <main class="content">
            <div id="tab-overview" class="tab-content active">
                <h2>Overview Dashboard</h2>
                <div class="stats-grid" id="overview-stats"></div>
                <div class="charts-grid">
                    <div class="chart-container">
                        <h3>Priority Distribution</h3>
                        <canvas id="priority-chart"></canvas>
                    </div>
                    <div class="chart-container">
                        <h3>Constraint Distribution</h3>
                        <canvas id="constraint-chart"></canvas>
                    </div>
                </div>
            </div>

            <div id="tab-variables" class="tab-content">
                <h2>Variables</h2>
                <div class="toolbar">
                    <button id="sort-name">Sort by Name</button>
                    <button id="sort-freq">Sort by Frequency</button>
                    <button id="sort-coeff">Sort by Coefficient</button>
                </div>
                <div class="variables-table" id="variables-table"></div>
            </div>

            <div id="tab-sections" class="tab-content">
                <h2>Document Sections</h2>
                <div class="sections-tree" id="sections-tree"></div>
            </div>

            <div id="tab-network" class="tab-content">
                <h2>Variable Network Graph</h2>
                <div class="network-controls">
                    <button id="reset-zoom">Reset Zoom</button>
                    <button id="toggle-labels">Toggle Labels</button>
                </div>
                <div id="network-graph"></div>
            </div>

            <div id="tab-statistics" class="tab-content">
                <h2>Statistical Analysis</h2>
                <div class="stats-grid" id="detailed-stats"></div>
                <div class="charts-grid">
                    <div class="chart-container">
                        <h3>Variable Categories</h3>
                        <canvas id="categories-chart"></canvas>
                    </div>
                    <div class="chart-container">
                        <h3>Sentence Length Distribution</h3>
                        <canvas id="sentence-chart"></canvas>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <div id="variable-detail-modal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <div id="variable-detail"></div>
        </div>
    </div>

    <script>
        window.appData = """
        + json.dumps(
            {
                "variables": variables,
                "statistics": statistics,
                "sections": sections,
                "graph": graph,
                "charts": charts,
            },
            indent=2,
        )
        + """;
    </script>
    <script src="js/app.js"></script>
    <script src="js/d3-graph.js"></script>
    <script src="js/charts.js"></script>
</body>
</html>"""
    )
    return html_template


def generate_html_interface():
    base_dir = Path(__file__).parent.parent.parent
    data_dir = base_dir / "constitution_analysis" / "data"
    web_dir = base_dir / "constitution_analysis" / "web"
    web_dir.mkdir(exist_ok=True)

    print("Loading data files...")
    variables = load_json(data_dir, "variables.json")
    statistics = load_json(data_dir, "statistics.json")
    sections = load_json(data_dir, "sections.json")
    graph = load_json(data_dir, "graph.json")
    charts = load_json(data_dir, "charts.json")

    print("Generating HTML interface...")
    html_content = render_html(variables, statistics, sections, graph, charts)

    output_path = web_dir / "index.html"
    with open(output_path, "w") as f:
        f.write(html_content)

    print(f"✓ HTML interface generated at {output_path}")
    print(f"  Open in browser: firefox {output_path}")


if __name__ == "__main__":
    generate_html_interface()
