#!/usr/bin/env python3
"""Build/verify script for Baby Checklist ESM refactor.

Checks JS module syntax and runs a quick verification of the static files.
To run: python3 build.py
To serve locally: python3 build.py --serve [port]
"""
import argparse
import http.server
import os
import sys
import json
from pathlib import Path

PUBLIC = Path(__file__).parent / "public"
JS_DIR = PUBLIC / "js"
DATA_DIR = JS_DIR / "data"


def check_js_modules():
    """Basic syntax check on all JS modules (import/export detection)."""
    issues = []
    for js_path in sorted(JS_DIR.rglob("*.js")):
        rel = js_path.relative_to(Path(__file__).parent)
        content = js_path.read_text(encoding="utf-8")
        # Basic ESM checks
        if content.strip().startswith("//") or content.strip().startswith("/*"):
            pass  # ok, doc comment
        has_imports = "import " in content
        has_exports = "export " in content

        # Check for top-level await or other potential issues
        if "export default" in content:
            issues.append(f"  ✗ {rel}: use named exports only (tree-shaking)")

        # Verify named export usage
        if has_exports and "export const" not in content and "export function" not in content:
            issues.append(f"  ? {rel}: has exports but no named export found")

        # Verify imports reference valid modules
        for line in content.split("\n"):
            if " from " in line and not line.strip().startswith("//"):
                pass  # Basic check

        status = "✓" if not any(i.startswith(f"  ✗ {rel}") for i in issues) else "✗"
        print(f"  {status} {rel}" + (" (ESM)" if has_imports or has_exports else ""))

    return issues


def check_html_modules():
    """Verify HTML files reference JS modules correctly."""
    html_files = list(PUBLIC.glob("*.html"))
    issues = []
    for html_path in sorted(html_files):
        rel = html_path.relative_to(Path(__file__).parent)
        content = html_path.read_text(encoding="utf-8")
        uses_module = 'type="module"' in content
        imports_js = "import " in content
        has_inline_script = "<script>" in content and "</script>" in content

        # Check for old-style inline API constant (should be imported now)
        old_api = "const API='/api/state'" in content or 'const API="/api/state"' in content
        if old_api:
            issues.append(f"  ✗ {rel}: still has inline API constant (should import from js/api.js)")

        # Check that module scripts have correct relative paths
        if uses_module:
            if "./js/" in content or "../js/" in content:
                print(f"  ✓ {rel} (ESM imports)")
            else:
                issues.append(f"  ? {rel}: has type=module but no js/ import path found")
        else:
            print(f"  . {rel} (no ESM refactor needed / served as-is)")

    return issues


def verify_data_modules():
    """Verify data modules have named exports and reasonable structure."""
    print("\n  [data modules]")
    # checklist.js
    checklist = (DATA_DIR / "checklist.js").read_text(encoding="utf-8")
    assert "export const CHECKLIST" in checklist, "checklist.js missing named export"
    # Count items by looking for id: pattern
    item_count = checklist.count("id: '") + checklist.count('id: "')
    assert item_count >= 14, f"CHECKLIST has only {item_count} items (expected 14+)"
    print(f"  ✓ js/data/checklist.js ({item_count} items, named export CHECKLIST)")

    # pediatras.js
    peds = (DATA_DIR / "pediatras.js").read_text(encoding="utf-8")
    assert "export const PEDIATRAS" in peds, "pediatras.js missing named export"
    assert "export const TIER_LABELS" in peds, "pediatras.js missing TIER_LABELS"
    ped_count = peds.count("name:")
    assert ped_count >= 9, f"PEDIATRAS has only {ped_count} items (expected 9+)"
    print(f"  ✓ js/data/pediatras.js ({ped_count} items, named exports PEDIATRAS, TIER_LABELS)")


def verify_state_json():
    """Verify state.json is valid JSON."""
    state_path = Path(__file__).parent / "state.json"
    try:
        with open(state_path) as f:
            data = json.load(f)
        print(f"  ✓ state.json (valid JSON, {len(data)} keys)")
    except Exception as e:
        print(f"  ✗ state.json: {e}")


def run_checks():
    print("=== Baby Checklist ESM Build Verification ===\n")
    print("  [JS modules]")
    js_issues = check_js_modules()
    print("\n  [HTML files]")
    html_issues = check_html_modules()
    verify_data_modules()
    verify_state_json()

    all_issues = js_issues + html_issues
    if all_issues:
        print("\n  Issues found:")
        for i in all_issues:
            print(i)
        return 1
    else:
        print("\n  ✓ All checks passed")
        return 0


def serve(port):
    """Serve the public directory for manual verification."""
    os.chdir(PUBLIC)
    handler = http.server.SimpleHTTPRequestHandler
    server = http.server.HTTPServer(("0.0.0.0", port), handler)
    print(f"\n🌸 Serving Baby Checklist at http://0.0.0.0:{port}")
    print(f"   (Press Ctrl+C to stop)\n")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n  Server stopped")
        return 0


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Baby Checklist build/verify")
    parser.add_argument("--serve", nargs="?", const=3001, type=int, help="Serve on a port (default: 3001)")
    args = parser.parse_args()

    if args.serve is not None:
        sys.exit(serve(args.serve))
    else:
        sys.exit(run_checks())