"""
Target resolver module.
Detects the type of scan target and routes accordingly.

Supported formats:
  - Local path:          ./project  or  /abs/path
  - GitHub URL:          https://github.com/org/repo
  - GitHub org:          org:stripe
  - Repo list file:      list:repos.txt
  - Path list file:      paths:targets.txt
"""

import re
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import List


class TargetType(str, Enum):
    LOCAL = "local"
    GITHUB_REPO = "github_repo"
    GITHUB_ORG = "github_org"
    REPO_LIST = "repo_list"
    PATH_LIST = "path_list"


@dataclass
class ResolvedTarget:
    """A fully resolved scan target."""
    type: TargetType
    value: str          # original input
    paths: List[str]    # expanded list of paths/URLs to scan


def resolve(target: str) -> ResolvedTarget:
    """
    Detect target type and return a ResolvedTarget.

    Args:
        target: Raw CLI argument string.

    Returns:
        ResolvedTarget with type and expanded paths.
    """
    # GitHub org prefix  e.g. org:stripe
    if target.startswith("org:"):
        org = target[4:].strip()
        return ResolvedTarget(type=TargetType.GITHUB_ORG, value=org, paths=[org])

    # Repo list file  e.g. list:repos.txt
    if target.startswith("list:"):
        file_path = Path(target[5:].strip())
        urls = _read_lines(file_path)
        return ResolvedTarget(type=TargetType.REPO_LIST, value=str(file_path), paths=urls)

    # Path list file  e.g. paths:targets.txt
    if target.startswith("paths:"):
        file_path = Path(target[6:].strip())
        paths = _read_lines(file_path)
        return ResolvedTarget(type=TargetType.PATH_LIST, value=str(file_path), paths=paths)

    # GitHub URL
    if re.match(r"^https?://github\.com/[\w.-]+/[\w.-]+/?$", target):
        return ResolvedTarget(type=TargetType.GITHUB_REPO, value=target, paths=[target])

    # Default: local path
    return ResolvedTarget(type=TargetType.LOCAL, value=target, paths=[target])


def _read_lines(file_path: Path) -> List[str]:
    """Read non-empty, non-comment lines from a file."""
    if not file_path.exists():
        raise FileNotFoundError(f"Target list file not found: {file_path}")
    lines = []
    for line in file_path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line and not line.startswith("#"):
            lines.append(line)
    return lines
