"""Model card generation for HuggingFace Hub."""

from __future__ import annotations

import json
from datetime import datetime, timezone


def generate_model_card(
    model_name: str,
    config_dict: dict,
    hardware_dict: dict | None = None,
    results: dict | None = None,
    dataset_name: str | None = None,
    language: str = "en",
    license_id: str = "apache-2.0",
    tags: list[str] | None = None,
) -> str:
    """Generate a HuggingFace model card (README.md) for a fine-tuned model.

    Returns Markdown string with YAML front matter.
    """
    tags = tags or []
    base_tags = ["bilgeai", "fine-tuned", "lora"]
    all_tags = list(dict.fromkeys(base_tags + tags))

    # YAML front matter
    lines = [
        "---",
        f"language: {language}",
        f"license: {license_id}",
        f"base_model: {model_name}",
        f"tags: {json.dumps(all_tags)}",
        "library_name: peft",
    ]

    if dataset_name:
        lines.append(f"datasets: [{dataset_name}]")

    lines.extend(["---", ""])

    # Title
    short_name = model_name.split("/")[-1] if "/" in model_name else model_name
    lines.append(f"# {short_name} (Fine-tuned with BilgeAI)")
    lines.append("")

    # Description
    lines.append("## Model Description")
    lines.append("")
    lines.append(
        f"This model is a fine-tuned version of [{model_name}]"
        f"(https://huggingface.co/{model_name}) "
        "using [BilgeAI](https://github.com/bugrabilge/bilge-ai)."
    )
    lines.append("")

    # Training details
    lines.append("## Training Details")
    lines.append("")

    key_params = [
        ("quantization", "Quantization"),
        ("lora_rank", "LoRA Rank"),
        ("lora_alpha", "LoRA Alpha"),
        ("batch_size", "Batch Size"),
        ("learning_rate", "Learning Rate"),
        ("num_epochs", "Epochs"),
        ("max_seq_length", "Max Sequence Length"),
        ("optimizer_name", "Optimizer"),
        ("lr_scheduler", "LR Scheduler"),
        ("seed", "Seed"),
    ]

    lines.append("| Parameter | Value |")
    lines.append("|-----------|-------|")
    for key, label in key_params:
        if key in config_dict:
            lines.append(f"| {label} | {config_dict[key]} |")
    lines.append("")

    # Results
    if results:
        lines.append("## Results")
        lines.append("")
        lines.append("| Metric | Value |")
        lines.append("|--------|-------|")
        if results.get("best_loss") is not None:
            lines.append(f"| Best Loss | {results['best_loss']:.4f} |")
        if results.get("final_loss") is not None:
            lines.append(f"| Final Loss | {results['final_loss']:.4f} |")
        if results.get("total_steps") is not None:
            lines.append(f"| Total Steps | {results['total_steps']} |")
        if results.get("training_time_seconds") is not None:
            mins = results["training_time_seconds"] / 60
            lines.append(f"| Training Time | {mins:.1f} min |")
        lines.append("")

    # Hardware
    if hardware_dict:
        lines.append("## Hardware")
        lines.append("")
        if hardware_dict.get("cpu_name"):
            lines.append(f"- **CPU**: {hardware_dict['cpu_name']}")
        if hardware_dict.get("ram_total_gb"):
            lines.append(f"- **RAM**: {hardware_dict['ram_total_gb']:.0f} GB")
        gpus = hardware_dict.get("gpus", [])
        if gpus:
            gpu = gpus[0] if isinstance(gpus[0], dict) else {}
            gpu_name = gpu.get("name", "Unknown")
            gpu_vram = gpu.get("vram_gb", 0)
            count = len(gpus)
            if count > 1:
                lines.append(f"- **GPU**: {count}x {gpu_name} ({gpu_vram:.0f} GB each)")
            else:
                lines.append(f"- **GPU**: {gpu_name} ({gpu_vram:.0f} GB)")
        lines.append("")

    # Dataset
    if dataset_name:
        lines.append("## Dataset")
        lines.append("")
        lines.append(
            f"Trained on [{dataset_name}](https://huggingface.co/datasets/{dataset_name})."
        )
        lines.append("")

    # Footer
    lines.append("## Framework")
    lines.append("")
    lines.append(
        "This model was fine-tuned using "
        "[BilgeAI](https://github.com/bugrabilge/bilge-ai) "
        "- Smart LLM Training Orchestrator."
    )
    lines.append("")
    timestamp = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    lines.append(f"*Generated on {timestamp}*")
    lines.append("")

    return "\n".join(lines)
