"""
Absfuyu: Resume
---------------
Resume Exporter

Version: 6.5.0
Date updated: 27/02/2026 (dd/mm/yyyy)
"""

# Module level
# ---------------------------------------------------------------------------
__all__ = ["Exporter"]


# Library
# ---------------------------------------------------------------------------
import json
from dataclasses import asdict
from typing import ClassVar, Protocol

from absfuyu.general.resume.models import CV


# Typing
# ---------------------------------------------------------------------------
class Exporter(Protocol):
    """
    CV Exporter
    """

    FORMAT_NAME: ClassVar[str]

    def export(self, cv: CV) -> str | bytes:
        """
        Export cv in different format

        Parameters
        ----------
        cv : CV
            CV instance

        Returns
        -------
        str | bytes
            Exported CV
        """
        ...


# Class
# ---------------------------------------------------------------------------
class ExportRegistry:
    _registry: dict[str, Exporter] = {}

    @classmethod
    def register(cls, exporter: Exporter) -> None:
        cls._registry[exporter.FORMAT_NAME] = exporter

    @classmethod
    def get(cls, name: str) -> Exporter:
        try:
            return cls._registry[name]()
        except KeyError:
            raise ValueError(f"Exporter '{name}' not registered.")


# Class - Export format
# ---------------------------------------------------------------------------
class MarkdownExporter:
    FORMAT_NAME = "markdown"

    def export(self, cv: CV) -> str:
        md = []

        # Header
        md.append(f"# {cv.personal.full_name}")

        if cv.personal.email:
            md.append(f"- Email: {cv.personal.email}")
        if cv.personal.phone:
            md.append(f"- Phone: {cv.personal.phone}")
        if cv.personal.location:
            md.append(f"- Location: {cv.personal.location}")

        if cv.personal.linkedin:
            md.append(f"- LinkedIn: {cv.personal.linkedin}")
        if cv.personal.github:
            md.append(f"- GitHub: {cv.personal.github}")

        md.append("\n---\n")

        # Summary
        if cv.summary:
            md.append("## Summary")
            md.append(cv.summary)
            md.append("")

        # Experience
        if cv.experiences:
            md.append("## Experience")
            for exp in cv.experiences:
                end = exp.end_date.isoformat() if exp.end_date else "Present"
                md.append(f"### {exp.role} — {exp.company}")
                md.append(f"{exp.start_date.isoformat()} - {end}")
                for ach in exp.achievements:
                    md.append(f"- {ach}")
                md.append("")

        # Education
        if cv.education:
            md.append("## Education")
            for edu in cv.education:
                md.append(f"**{edu.degree}**, {edu.institution} " f"({edu.start_year}-{edu.end_year})")
            md.append("")

        # Skills
        if cv.skills:
            md.append("## Skills")
            md.append(", ".join(cv.skills))
            md.append("")

        # Projects
        if cv.projects:
            md.append("## Projects")
            for proj in cv.projects:
                md.append(f"### {proj.name}")
                md.append(proj.description)
                if proj.technologies:
                    md.append(f"Technologies: {', '.join(proj.technologies)}")
                md.append("")

        return "\n".join(md)


class DictExporter:
    FORMAT_NAME = "dict"

    def export(self, cv: CV) -> str:
        return asdict(cv)


class JSONExporter:
    FORMAT_NAME = "json"

    def export(self, cv: CV) -> str:
        return json.dumps(asdict(cv), indent=4, default=str)


# # Class - Register export format
# # ---------------------------------------------------------------------------
# ExportRegistry.register(DictExporter)
# ExportRegistry.register(JSONExporter)
# ExportRegistry.register(MarkdownExporter)
