from __future__ import annotations
from dataclasses import dataclass, field, asdict
from typing import Any


@dataclass
class RepositoryNode:
    id: str
    name: str
    path: str
    languages: list[str]
    branch: str
    line_count: int
    file_count: int
    created_at: float
    updated_at: float
    type: str = "repository"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> RepositoryNode:
        return cls(**data)


@dataclass
class ModuleNode:
    id: str
    name: str
    path: str
    parent: str | None
    line_count: int
    file_count: int
    language: str
    crate: str = ""
    # Whether the module is publicly accessible from its parent (e.g. Rust
    # ``pub mod foo`` vs ``mod foo``).  Directory modules default to True for
    # non-Rust languages; Rust file-level ``mod`` declarations set this based
    # on their visibility.
    is_exported: bool = True
    type: str = "module"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> ModuleNode:
        return cls(**data)


@dataclass
class ClassNode:
    id: str
    name: str
    kind: str
    file_id: str
    module_id: str
    line_start: int
    line_end: int
    visibility: str
    bases: list[str]
    docstring: str | None
    methods: list[str] = field(default_factory=list)
    is_exported: bool = True
    cfg_conditions: list[str] = field(default_factory=list)
    # Language-specific semantic module path (see FunctionNode.module_path).
    module_path: str | None = None
    is_definition: bool = True
    byte_start: int | None = None
    byte_end: int | None = None
    type: str = "class"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> ClassNode:
        return cls(**data)


@dataclass
class FunctionNode:
    id: str
    name: str
    signature: str
    file_id: str
    module_id: str
    class_id: str | None
    line_start: int
    line_end: int
    visibility: str
    is_async: bool
    is_static: bool
    is_test: bool
    params: list[dict]
    return_type: str | None
    docstring: str | None
    summary: str | None = None
    class_name: str | None = None
    body: str | None = None
    is_exported: bool = True
    cfg_conditions: list[str] = field(default_factory=list)
    # Unresolved parser facts used to rebuild cross-file CALL edges.  Keeping
    # these on the node makes relation resolution independent of parser order
    # and lets incremental builds restore incoming relations without reparsing
    # unchanged files.
    calls: list[str] = field(default_factory=list)
    # Source-ranged unresolved relation evidence.  These facts let the
    # resolver use receivers and local type bindings instead of relying on a
    # repository-global name match.
    references: list[dict[str, Any]] = field(default_factory=list)
    type_bindings: list[dict[str, Any]] = field(default_factory=list)
    linkage: str | None = None
    # Language-specific semantic module path (e.g. Rust inline ``mod sync_impl``).
    # Enables CLI/MCP to display and disambiguate symbols from different inline
    # modules (e.g. sync_impl::Body vs async_impl::Body).
    module_path: str | None = None
    is_definition: bool = True
    byte_start: int | None = None
    byte_end: int | None = None
    kind: str = "function"
    type: str = "function"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> FunctionNode:
        return cls(**data)


@dataclass
class FileNode:
    id: str
    path: str
    language: str
    line_count: int
    is_test: bool
    is_generated: bool
    md5: str
    crate: str = ""
    # Serialized ImportInfo values.  The default keeps graphs written before
    # relation facts were persisted fully loadable.
    imports: list[dict[str, Any]] = field(default_factory=list)
    # Symbol names re-exported via ``pub use`` (Rust).  Used by
    # get_module_contents to surface re-exported API from private modules.
    reexports: list[str] = field(default_factory=list)
    # Whether the file is a private mod (``mod foo;`` without ``pub``).
    # Symbols in private-mod files are not public API unless re-exported.
    is_exported: bool = True
    parse_status: str = "ok"
    semantic_backend: str = ""
    semantic_facts: int = 0
    parse_coverage: float = 1.0
    parser_name: str = ""
    parser_version: str = ""
    source_bytes: int = 0
    parsed_bytes: int = 0
    parse_diagnostics: list[dict[str, Any]] = field(default_factory=list)
    type: str = "file"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> FileNode:
        return cls(**data)


@dataclass
class DocumentNode:
    id: str
    title: str
    path: str
    format: str
    line_count: int
    md5: str
    input_md5: str = ""
    summary: str | None = None
    section_titles: list[str] = field(default_factory=list)
    content: str | None = None
    content_state: str = "not_selected"
    content_complete: bool = False
    content_bytes: int = 0
    content_encoding: str = "utf-8"
    content_representation: str = "source_text"
    type: str = "document"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> DocumentNode:
        return cls(**data)


@dataclass
class SectionNode:
    id: str
    title: str
    level: int
    doc_id: str
    line_start: int
    line_end: int
    content: str
    summary: str | None = None
    type: str = "section"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> SectionNode:
        return cls(**data)


@dataclass
class DocumentChunkNode:
    id: str
    doc_id: str
    section_id: str | None
    title: str
    line_start: int
    line_end: int
    char_start: int
    char_end: int
    type: str = "document_chunk"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> DocumentChunkNode:
        return cls(**data)


@dataclass
class ConceptNode:
    id: str
    name: str
    source: str
    description: str | None = None
    type: str = "concept"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> ConceptNode:
        return cls(**data)


@dataclass
class TestNode:
    # Domain model, not a pytest test container.
    __test__ = False

    id: str
    name: str
    file_id: str
    framework: str
    targets: list[str]
    line_start: int
    line_end: int
    type: str = "test"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> TestNode:
        return cls(**data)


@dataclass
class CommitNode:
    id: str
    sha: str
    author: str
    email: str
    timestamp: float
    message: str
    files_changed: int
    files: list[str] = field(default_factory=list)
    type: str = "commit"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> CommitNode:
        return cls(**data)


@dataclass
class PRNode:
    id: str
    number: int
    title: str
    author: str
    timestamp: float
    state: str
    commit_ids: list[str]
    type: str = "pr"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> PRNode:
        return cls(**data)


@dataclass
class ConventionNode:
    id: str
    category: str
    name: str
    description: str
    source: str
    scope: str | None = None
    type: str = "convention"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> ConventionNode:
        return cls(**data)


@dataclass
class CodeChunkNode:
    id: str
    content: str
    kind: str
    source_id: str
    line_start: int
    line_end: int
    token_count: int
    keywords: str
    type: str = "code_chunk"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> CodeChunkNode:
        return cls(**data)


@dataclass
class CodeSymbolNode:
    """A macro, alias, field, variable, or enum-constant occurrence."""

    id: str
    name: str
    kind: str
    file_id: str
    module_id: str
    line_start: int
    line_end: int
    byte_start: int
    byte_end: int
    visibility: str = "public"
    signature: str | None = None
    value: str | None = None
    data_type: str | None = None
    owner_name: str | None = None
    owner_id: str | None = None
    is_definition: bool = True
    is_exported: bool = True
    cfg_conditions: list[str] = field(default_factory=list)
    references: list[dict[str, Any]] = field(default_factory=list)
    type: str = "symbol"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> CodeSymbolNode:
        return cls(**data)


@dataclass
class DiffNode:
    id: str
    commit_id: str
    file_path: str
    change_type: str
    before: str | None
    after: str | None
    changed_functions: list[str]
    type: str = "diff"

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> DiffNode:
        return cls(**data)


@dataclass
class Edge:
    id: str
    type: str
    source: str
    target: str
    properties: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> Edge:
        return cls(**data)


NODE_TYPES: dict[str, type] = {
    "repository": RepositoryNode,
    "module": ModuleNode,
    "class": ClassNode,
    "function": FunctionNode,
    "file": FileNode,
    "document": DocumentNode,
    "section": SectionNode,
    "document_chunk": DocumentChunkNode,
    "concept": ConceptNode,
    "test": TestNode,
    "commit": CommitNode,
    "pr": PRNode,
    "convention": ConventionNode,
    "code_chunk": CodeChunkNode,
    "symbol": CodeSymbolNode,
    "diff": DiffNode,
}