#!/usr/bin/env python3.12
"""
Read DESIGNED.md and propose unused seed/style combinations.
Annotate the latest or specified batch file with planned combinations.
"""
from __future__ import annotations

import argparse
import json
import pathlib
import random
import re
from typing import Dict, List

# Default fallback if seeds.json not found
DEFAULT_SUGGESTIONS = [
    "brutalist neon grids",
    "soft serif editorial",
    "glassmorphism minimal",
    "kinetic monochrome",
    "retro vapor gradients",
    "bauhaus primary blocks",
    "cinematic duotone",
    "illustrated collage",
    "architectural linework",
    "playful geometrics",
]


def load_vocabulary(root: pathlib.Path) -> Dict[str, List[str]]:
    """Load vocabulary from seeds.json."""
    seeds_file = root / "tools" / "design" / "seeds.json"
    if seeds_file.exists():
        try:
            data = json.loads(seeds_file.read_text(encoding="utf-8"))
            return data.get("vocabulary", {})
        except (json.JSONDecodeError, KeyError):
            pass
    return {}


def generate_composite_style(vocabulary: Dict[str, List[str]]) -> str:
    """Generate a random composite style from vocabulary."""
    if not vocabulary:
        return "random-style"
    
    parts = []
    # Define preferred order
    keys = ["aesthetic", "layout", "typography", "palette", "patterns", "imagery", "motifs", "tone"]
    
    for key in keys:
        if key in vocabulary and vocabulary[key]:
            val = random.choice(vocabulary[key])
            parts.append(f"{key}: {val}")
            
    return ", ".join(parts)


def load_temp_dir(root: pathlib.Path) -> pathlib.Path:
    cfg = root / ".wdmaker" / "config.toml"
    if not cfg.exists():
        return pathlib.Path(f"/Volumes/Temp/WDMaker/{root.name}/")
    text = cfg.read_text()
    for line in text.splitlines():
        if line.strip().startswith("temp_dir"):
            val = line.split("=", 1)[1].strip().strip('"').strip("'")
            return pathlib.Path(val)
    return pathlib.Path(f"/Volumes/Temp/WDMaker/{root.name}/")


def read_designed(designed_md: pathlib.Path) -> Dict[str, str]:
    seeds: Dict[str, str] = {}
    if not designed_md.exists():
        return seeds
    for line in designed_md.read_text(encoding="utf-8").splitlines():
        if not line.startswith("|") or "Domain" in line or "--------" in line:
            continue
        cols = [c.strip() for c in line.strip("|").split("|")]
        if len(cols) >= 2:
            seeds[cols[0]] = cols[1]
    return seeds


def annotate_batch(batch_path: pathlib.Path, plans: Dict[str, str]) -> None:
    lines = batch_path.read_text(encoding="utf-8").splitlines()
    out: List[str] = []
    out.extend(lines)
    out.append("")
    out.append("## Planned Seeds/Styles")
    out.append("")
    out.append("| Domain | Planned Seed/Style |")
    out.append("|--------|----------------------|")
    for domain, seed in plans.items():
        out.append(f"| {domain} | {seed} |")
    out.append("")
    batch_path.write_text("\n".join(out), encoding="utf-8")


def find_batch_files(batch_dir: pathlib.Path) -> List[pathlib.Path]:
    files = list(batch_dir.glob("Batch_*.md"))
    files.extend(batch_dir.glob("batch-*-design.md"))
    return sorted(files)


def main() -> int:
    parser = argparse.ArgumentParser(description="Propose unused seed/style combos and annotate batch.")
    parser.add_argument("--root", default=".", help="Repo root (default: .)")
    parser.add_argument("--batch-id", help="Batch ID to annotate (default: latest Batch_*.md)")
    parser.add_argument("--count", type=int, default=5, help="How many combos to propose (ignored, does all in batch)")
    args = parser.parse_args()

    root = pathlib.Path(args.root).resolve()
    
    # Load vocabulary from seeds.json
    vocabulary = load_vocabulary(root)

    batch_files = find_batch_files(root / ".smbatcher" / "batches")
    if not batch_files:
        print("ERROR:no_batch_files:.smbatcher/batches")
        return 2
    batch_path = None
    if args.batch_id:
        candidate = root / ".smbatcher" / "batches" / f"Batch_{args.batch_id}.md"
        if candidate.exists():
            batch_path = candidate
    if batch_path is None:
        batch_path = batch_files[-1]

    domains_in_batch: List[str] = []
    for line in batch_path.read_text(encoding="utf-8").splitlines():
        if line.startswith("|") and "Domain" not in line and "--------" not in line:
            cols = [c.strip() for c in line.strip("|").split("|")]
            if len(cols) >= 1:
                domains_in_batch.append(cols[0])

    plans = {}
    for domain in domains_in_batch:
        plans[domain] = generate_composite_style(vocabulary)

    if not plans:
        print("OK:no_plans_generated")
        return 0

    annotate_batch(batch_path, plans)
    print(f"OK:annotated:{len(plans)} domains in {batch_path.name}")
    return 0


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