import argparse
import sys
import os
from pathlib import Path
from .core import VacationExtender

# --- Default Configuration Template ---
# This string ensures that users installing via pip can generate 
# a valid config file anywhere without needing external file assets.
CONFIG_TEMPLATE = """# =================================================================
# VACATION EXTENDER CONFIGURATION
# Generated by VacationExtender
# Source: https://github.com/afsmaira/vacationExtender
# =================================================================

[CALENDAR]
# The target year (Integer). Default: next year
year = 2026

# Weekend definition (0 = Mon, 6 = Sun). Default: [5, 6] (Sat, Sun)
weekend = [5, 6]

[LOCATION]
# ISO 3166-1 alpha-2 country code (e.g., "BR", "US", "CA")
country_code = "BR"

# Subdivision code (State/Province). Use "" for none.
subdivision_code = "SP"

# Observe holidays falling on weekends on the next workday? (True/False)
include_observed = false

[CONSTRAINTS]
# Total vacation days available in the budget
vacation_days = 30

# Maximum number of distinct vacation periods allowed
max_vac_periods = 3

# Minimum/Maximum days per single break (PTO + Holidays + Weekend)
min_vac_days_per_break = 5
max_vac_days_per_break = 20

# Minimum days gap between two vacation periods
min_gap_days = 60

# Number of suggestions to display
top_n_suggestions = 1

# Additional holidays (e.g., local holidays or company bridges).
# Accepted formats in the list:
#   - Single day: "YYYY-MM-DD"
#   - Interval:   "YYYY-MM-DD:YYYY-MM-DD" (Start:End)
custom_holidays = []

# Mandatory work days or intervals (dates where you CANNOT take vacation).
# Same format as custom_holidays.
forced_work = []

# List of specific dates where you are already committed to being on vacation.
# The engine will prioritize these dates and calculate extensions around them.
# Same format as custom_holidays.
must_be_vacation = []

[ALGORITHM]
# 'optimal' (Slow, Perfect) or 'greedy' (Fast, Heuristic)
algorithm_type = "optimal"

# Alpha Factor (0.0 to 1.0). 
# Higher values prefer longer consecutive breaks over total days off.
duration_weight_factor_alpha = 0.5
"""


def create_default_config(path):
    with open(path, "w", encoding="utf-8") as f:
        f.write(CONFIG_TEMPLATE)


def parse_args():
    parser = argparse.ArgumentParser(
        description="Vacation Extender - Maximize your time off."
    )

    parser.add_argument(
        "-c", "--config",
        type=str,
        default="config.toml",
        help="Path to the configuration file (default: config.toml)"
    )

    subparsers = parser.add_subparsers(
        dest="command", help="Available commands"
    )

    # Command 'init'
    subparsers.add_parser(
        "init", help="Create a template config.toml file"
    )

    args = parser.parse_args()

    if args.command == "init":
        target = Path("config.toml")
        if target.exists():
            print("❌ 'config.toml' already exists here. I won't overwrite it.")
            sys.exit(1)
        create_default_config(target)
        print("✅ Created default 'config.toml'. Edit it and run 'vacationext'.")
        sys.exit(0)

    config_path = args.config

    if not os.path.exists(config_path):
        print(f"❌ Configuration file '{config_path}' not found.")
        print("Run 'vacationext init' to generate one.")
        sys.exit(1)
    return args


def main():
    ve = VacationExtender(parse_args().config)
    ve.run()
    print(ve)


if __name__ == "__main__":
    main()
