#!/usr/bin/env python3.12
"""
Read and display Design.md with structured output.

Features:
- Extract and display individual sections
- Show metadata summary (colors, fonts, seed)
- Validate structure while reading
- Multiple output formats
"""
from __future__ import annotations

import argparse
import pathlib
import re
import sys
from typing import Optional, List, Dict

REQUIRED_HEADINGS = [
    "## Aesthetics and Tone",
    "## Layout Motifs and Structure",
    "## Typography and Palette",
    "## Imagery and Motifs",
    "## Prompts for Implementation",
    "## Uniqueness Notes",
]


def extract_sections(text: str) -> Dict[str, str]:
    """Extract content for each section."""
    sections: Dict[str, str] = {}

    for heading in REQUIRED_HEADINGS:
        pattern = re.compile(
            rf"{re.escape(heading)}\s*(.*?)(?=^##|\Z)",
            re.DOTALL | re.MULTILINE
        )
        match = pattern.search(text)
        if match:
            sections[heading] = match.group(1).strip()
        else:
            sections[heading] = ""

    return sections


def extract_title(text: str) -> Optional[str]:
    """Extract title from first heading."""
    match = re.search(r"^#\s+(.+)$", text, re.MULTILINE)
    if match:
        return match.group(1).strip()
    return None


def extract_colors(text: str) -> List[str]:
    """Extract hex colors."""
    return list(set(re.findall(r"#[0-9A-Fa-f]{6}\b", text)))


def extract_fonts(text: str) -> List[str]:
    """Extract font names."""
    font_pattern = r"(Inter|Helvetica|Roboto|Open Sans|Lato|Montserrat|Poppins|Space|IBM Plex|JetBrains|Georgia|Merriweather|Playfair|Lora|Work Sans|Canela|Cormorant|Sora|Futura)"
    fonts = re.findall(font_pattern, text, re.IGNORECASE)
    return list(dict.fromkeys(fonts))


def extract_stamp_info(text: str) -> Dict[str, str]:
    """Extract stamp metadata."""
    info: Dict[str, str] = {}

    patterns = {
        "timestamp": r"timestamp:\s*([^\n]+)",
        "domain": r"domain:\s*([^\n]+)",
        "seed": r"seed:\s*([^\n]+)",
        "content_hash": r"content_hash:\s*([^\n]+)",
    }

    for key, pattern in patterns.items():
        match = re.search(pattern, text)
        if match:
            info[key] = match.group(1).strip()

    return info


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Read and display Design.md",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s sites/example.com-v1/DESIGN.md
  %(prog)s sites/example.com-v1/DESIGN.md --section "Aesthetics"
  %(prog)s sites/example.com-v1/DESIGN.md --summary
  %(prog)s sites/example.com-v1/DESIGN.md --prompts
        """
    )
    parser.add_argument("path", help="Path to Design.md")
    parser.add_argument("--section", "-s", help="Show specific section (partial match)")
    parser.add_argument("--summary", action="store_true", help="Show metadata summary only")
    parser.add_argument("--prompts", action="store_true", help="Show implementation prompts only")
    parser.add_argument("--colors", action="store_true", help="Show colors only")
    parser.add_argument("--fonts", action="store_true", help="Show fonts only")
    parser.add_argument("--raw", action="store_true", help="Show raw content without formatting")
    args = parser.parse_args()

    path = pathlib.Path(args.path)
    if not path.exists():
        print(f"ERROR:file_not_found:{path}")
        return 2

    text = path.read_text(encoding="utf-8")

    # Raw output
    if args.raw:
        print(text)
        return 0

    # Extract metadata
    title = extract_title(text)
    sections = extract_sections(text)
    colors = extract_colors(text)
    fonts = extract_fonts(text)
    stamp = extract_stamp_info(text)

    # Colors only
    if args.colors:
        if colors:
            for color in colors:
                print(color)
        else:
            print("No colors found")
        return 0

    # Fonts only
    if args.fonts:
        if fonts:
            for font in fonts:
                print(font)
        else:
            print("No fonts found")
        return 0

    # Summary only
    if args.summary:
        print(f"{'=' * 60}")
        print(f"DESIGN SUMMARY: {path.parent.name}")
        print(f"{'=' * 60}")
        print()
        if title:
            print(f"Title: {title}")
        if stamp.get("seed"):
            print(f"Seed: {stamp['seed']}")
        if stamp.get("timestamp"):
            print(f"Stamped: {stamp['timestamp']}")
        if stamp.get("content_hash"):
            print(f"Hash: {stamp['content_hash']}")
        print()
        print(f"Colors ({len(colors)}): {', '.join(colors[:5]) if colors else 'none'}")
        print(f"Fonts ({len(fonts)}): {', '.join(fonts) if fonts else 'none'}")
        print()
        print("Sections:")
        for heading in REQUIRED_HEADINGS:
            content = sections.get(heading, "")
            status = "✓" if content and "(placeholder" not in content.lower() else "✗"
            chars = len(content)
            print(f"  {status} {heading[3:]}: {chars} chars")
        return 0

    # Prompts only
    if args.prompts:
        prompts = sections.get("## Prompts for Implementation", "")
        if prompts:
            print(prompts)
        else:
            print("No implementation prompts found")
        return 0

    # Specific section
    if args.section:
        search = args.section.lower()
        for heading, content in sections.items():
            if search in heading.lower():
                print(f"{heading}")
                print("-" * len(heading))
                print()
                print(content if content else "(empty)")
                return 0
        print(f"FAIL:section_not_found:{args.section}")
        return 1

    # Full output with formatting
    print(f"{'=' * 60}")
    if title:
        print(title)
    print(f"{'=' * 60}")
    print()

    # Show stamp info if present
    if stamp:
        print("Metadata:")
        for key, value in stamp.items():
            print(f"  {key}: {value}")
        print()

    # Show extracted info
    if colors:
        print(f"Colors: {', '.join(colors[:8])}")
    if fonts:
        print(f"Fonts: {', '.join(fonts)}")
    if colors or fonts:
        print()

    # Show sections
    for heading in REQUIRED_HEADINGS:
        content = sections.get(heading, "")
        print(f"{heading}")
        print("-" * len(heading))
        if content:
            # Truncate long sections for readability
            if len(content) > 500:
                print(content[:500] + "...")
                print(f"[truncated - {len(content)} chars total]")
            else:
                print(content)
        else:
            print("(not found)")
        print()

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
