"""TypeScript source file analyzer -- assembles all metrics."""

from __future__ import annotations

from pathlib import Path

from vibelexity.analyzers.common import AnalyzerConfig, analyze_source_generic
from vibelexity.analyzers.shared import create_analyze_file
from vibelexity.models import FileComplexity
from vibelexity.parsers.typescript import (
    parse,
    collect_functions,
    func_name,
    func_param_count,
)
from vibelexity.metrics.lloc.typescript import count_lloc
from vibelexity.metrics.halstead.typescript import compute_halstead_ts
from vibelexity.metrics.npath.typescript import compute_npath_ts
from vibelexity.metrics.dtd.typescript import compute_dtd_ts
from vibelexity.metrics.cognitive.typescript import compute_cognitive_ts
from vibelexity.metrics.cyclomatic.typescript import compute_cyclomatic_ts
from vibelexity.metrics.duplication.config import TYPESCRIPT_CONFIG


def get_tsx_flag(filepath: str | Path) -> bool:
    """Determine if file should be parsed as TSX."""
    return Path(filepath).suffix.lower() == ".tsx"


def analyze_source(code: str, tsx: bool = False) -> FileComplexity:
    config = AnalyzerConfig(
        parse_fn=lambda c: parse(c, tsx=tsx),
        collect_functions_fn=collect_functions,
        func_name_fn=func_name,
        func_param_count_fn=func_param_count,
        compute_cognitive_fn=compute_cognitive_ts,
        compute_halstead_fn=compute_halstead_ts,
        compute_npath_fn=compute_npath_ts,
        compute_dtd_fn=compute_dtd_ts,
        compute_cyclomatic_fn=compute_cyclomatic_ts,
        count_lloc_fn=count_lloc,
        dup_config=TYPESCRIPT_CONFIG,
    )
    return analyze_source_generic(code, config)


def analyze_file(filepath: str) -> FileComplexity:
    """Analyze a file and return cognitive complexity scores."""
    tsx = get_tsx_flag(filepath)
    path = Path(filepath)
    source = path.read_text()
    result = analyze_source(source, tsx=tsx)
    result.path = str(path)
    return result
